Roku Developer Program

Join our online forum to talk to Roku developers and fellow channel creators. Ask questions, share tips with the community, and find helpful resources.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
renojim
Community Streaming Expert

Re: number of viewers query

If you're getting 500 errors, I would guess there's a syntax error in your PHP or a file permissions problem on your server. Can you post your PHP code and your BrS code that interfaces with it?

-JT
Roku Community Streaming Expert

Help others find this answer and click "Accept as Solution."
If you appreciate my answer, maybe give me a Kudo.

I am not a Roku employee.
0 Kudos
kjg
Visitor

Re: number of viewers query

sure:

can we use this file from the server?
  it interfaces with a web page so multiple devices can enter their count. it works well.
here is the server side script:
<?php
    if(isset($_POST['customMethod']))
    {
        if(isset($_POST['numviewers']))
        {
            //Write the data to the file
            $file = @fopen("count.txt", "r+");
            
            if($file == false)
            {
                $file = fopen("count.txt", "w+");
            }
            
            $numViewers = $_POST['numviewers'];
            
            $count = fgets($file);
            
            if(($count == NULL) || ($count == ""))
            {
                //First entry in the file, just write to it
                fwrite($file, $numViewers);
            }
            
            else
            {
                //Increment and then write to the file
                $count = intval($count);
                $count += $numViewers;
                
                //Write back to the file
                fclose($file);
                $file = fopen("count.txt", "w+");
                fwrite($file, $count);
            }
            
            fclose($file);
        }
        
        else
        {
            echo "<h2>Incorrect Call</h2>";
        }
    }
    
    else
    {
        echo "<h2>Incorrect Call</h2>";
    }
?>


here is my Task file. I have tried several different ways so it is a mess right now. I was asked not to post real URL. so it is a close resemblance.
<?xml version="1.0" encoding="utf-8" ?>
<component name="NumTransfer" extends="Task">


    
  <script type="text/brightscript">
    <![CDATA[
sub init()
      'print " in NumTransfer"
      'Print " Pin is "m.global.NumViewers
        m.top.functionName = "go2"
      end sub

      sub go2()
    timeout%  = 2000
    numviewers = m.global.NumViewers
    'customMethod = m.global.NumViewers    
    numViewers = m.global.NumViewers
    roRequest = CreateObject("roURLTransfer")
    roRequest.setUrl("http://anAdderss.com:8080/formprocessor.php")       
    sleep(2000)    
    print "In NumTransfer"      
    roPort = CreateObject("roMessagePort")  
    roRequest.setPort(roPort)             
    print "after setting the port"  
    if (roRequest.AsyncPostFromString(numviewers))            
            roEvent = wait(timeout%, roRequest.GetPort())                        
            print "roEvent " roEvent
            print "numviewers =" numviewers
            if type(roEvent) = "roUrlEvent"
                str = roEvent.GetString()                
                int = roEvent.GetInt()
                print "I am Transferring NumViewers"
                print "roEvent.GetResponseCode()" roEvent.GetResponseCode()
                print "str = " str                
                print "Int =" int                
            else if roEvent = invalid
                roRequest.AsyncCancel()  'reset the connection on timeouts
                print "Unknown"
            else
                print "roUrlTransfer::AsyncPostFromString(): unknown event"
            endif
     end if
    
    
     DeviceInfo  = CreateObject("roDeviceInfo")
        IPAddr      = DeviceInfo.getIPAddrs()
        transfer    = createObject("roUrlTransfer")
        for each item in IPAddr
        
          url       = "http://" + IPAddr[item]  + ":8060/keypress/Back"
          transfer.setUrl(url)
          transfer.PostFromString("")
          
          url       = "http://" + IPAddr[item]  + ":8060/keypress/Back"
          transfer.setUrl(url)
          transfer.PostFromString("")
        end for
    end sub
]]>
    
  </script>
   
  </component>

         

here is the web form that goes with the php server script: It works well.
<html>
    <head>
        <title>Input Number Of Viewers</title>
        
        <script type="text/javascript">
            function processForm()
            {
                //Get the number of viewers from the entry in the form
                var numViewers = document.getElementById("numviewers").value;

                if(numViewers.length > 0)
                {
                    if(numViewers.match(/^[0-9]+$/g))
                    {
                        //Send the report to the php processor
                        var xmlhttp = new XMLHttpRequest();
                        var url = "formprocessor.php";
                        
                        var data = new FormData();
                        data.append('customMethod', 'updateCounter');
                        data.append('numviewers', numViewers);

                        xmlhttp.onreadystatechange = function()
                        {
                            if (xmlhttp.readyState == XMLHttpRequest.DONE )
                            {
                               if (xmlhttp.status == 200)
                               {
                                   window.location.href = "hls_progressive.html";
                               }
                               
                               else if (xmlhttp.status == 400)
                               {
                                  alert('There was an error 400');
                               }
                               
                               else
                               {
                                   alert('something else other than 200 was returned');
                               }
                            }
                        };

                        xmlhttp.open("POST", url, false);
                        xmlhttp.send(data);
                    }
                }
                
                return false;
            }
        </script>
        
        <style>
            .content
            {
                position: relative;
            }
            
            .formdiv
            {
                background: #CCC;
                border: 1px solid #000;
                left: 30%;
                height: 150px;
                margin: 0 auto;
                padding: 0 0;
                position: absolute;
                text-align: center;
                top: 50%;
                transform: translateY(100%);
                width: 40%;
            }
        </style>
    </head>
    
    <body>
        <div class="content">
            <div class="formdiv">
                <form class="viewerform" method="POST" onsubmit="return processForm();">
                    <p>Please Enter the Number of People that will be Viewing this Meeting</p>
                    <label for="numviewers">Number Of Viewers: <input type="text" name="numviewers" id="numviewers"></label><br><br>
                    <span class="viewerformbuttonspan"><input type="submit" value="Submit"></span>
                </form>
            </div>
        </div>
    </body>
</html>




the task component actually returns a 200 code with a 1 for event. so it looks like it goes through. But, the field is never added.
I get and "<h2>Incorrect Call</h2>" for the string. I see it at the bottom of the server script.
the other code that you suggested was just appended to the original php script. I didn't do it. someone else who has access to the server did.

thanks!!!
0 Kudos
belltown
Roku Guru

Re: number of viewers query

"kjg" wrote:
it is a mess right now

... that is the problem.

Try this:

MainScene.xml:

<?xml version="1.0" encoding="UTF-8"?>

<component name="MainScene" extends="Scene">

 <script type="text/brightscript" uri="pkg:/components/MainScene.brs" />

 <children>

   <Label
     id="label"
     text=""
     width="1280"
     height="720"
     vertAlign="center"
     horizAlign="center"
     font="font:LargeBoldSystemFont" />
     
   <NumViewersTask id="numViewersTask" />

 </children>

</component>


MainScene.brs:

sub init()
   m.label = m.top.findNode("label")
    m.numViewersTask = m.top.findNode("numViewersTask")
   m.top.dialog = CreateObject("roSGNode", "PinDialog")
   m.top.dialog.title = "Enter Number of Viewers"
   m.top.dialog.buttons = ["OK", "Cancel"]
   m.top.dialog.setFocus(true)
   m.top.dialog.pinPad.pinLength = 3
   m.top.dialog.pinPad.secureMode = false
   m.top.dialog.ObserveField("buttonSelected", "onButtonSelected")
end sub

sub onButtonSelected()
   if m.top.dialog.buttonSelected = 0
       pin = m.top.dialog.pin
       m.label.text = "Viewers Entered: " + pin
       m.numViewersTask.numViewers =  pin.ToInt()
       m.numViewersTask.control = "RUN"
   else
       m.label.text = "Cancelled"
   end if
   m.top.dialog.close = true
end sub


NumViewersTask.xml:

<?xml version="1.0" encoding="UTF-8"?>

<component name="NumViewersTask" extends="Task">

 <script type="text/brightscript" uri="pkg:/components/NumViewersTask.brs" />

 <interface>
   <field id="numViewers" type="integer" alwaysNotify="true" />
 </interface>

</component>


NumViewersTask.brs:

sub init()
   m.top.functionName = "taskRun"
end sub

function taskRun() as void

   print "numViewers: "; m.top.numViewers

   if Type(m.top.numViewers) <> "roInt"
       print "Invalid type: "; Type(m.top.numViewers)
       return
   end if

   if m.top.numViewers <= 0
       print "No viewers"
       return
   end if

   port    = CreateObject("roMessagePort")
   ut      = CreateObject("roUrlTransfer")
   url     = "http://server.com/script.php"
   query   = "customMethod=updateCounter&numviewers=" + m.top.numViewers.ToStr()

   ut.SetPort(port)
   ut.SetUrl(url)
   ut.AsyncPostFromString(query)

   while true
       msg = Wait(0, port)
       if Type(msg) = "roUrlEvent"
           if msg.GetInt() = 1
               responseCode = msg.GetResponseCode()
               failureReason = msg.GetFailureReason()
               if responseCode = 200
                   print "Success"
               else
                   print "Failed. responseCode: "; responseCode; ". failureReason: "; failureReason
               end if
           else
               ut.AsyncCancel()
               print "roUrlTransfer did not complete"
           end if
           exit while
       end if
   end while

end function
0 Kudos
kjg
Visitor

Re: number of viewers query

Awesome!
I will give it a shot and get back with results!
I do appreciate it!!
0 Kudos
kjg
Visitor

Re: number of viewers query

The line with the query in it took care of it. works like a charm!!
Just buttoning it up and all is done!

I should have cleaned up the code a bit before posting but I was getting frustrated with my own lack of understanding.
Thank you very much for your valued input.
I am new to this & you gave me a solid boost!

thank you Belltown !!!
0 Kudos
EnTerr
Roku Guru

Re: number of viewers query

"renojim" wrote:
renojim:I admit it makes more sense to use POST.  Maybe someday I'll change my approach, but I'll probably stick with queries.  Then again, does it make sense to POST nothing in a query or to even POST a query in the first place?  🙂

Sure - POST is in no way exclusive to application/x-www-form-urlencoded form encoding. The verb (method), the URL and the body encoding are orthogonal, we can say^. Notice i am not dogmatic about this, as long as one understands the differences. The "MUST" part on when to choose what is like training wheels.

"renojim" wrote:
Ok, I think I'm going to change my code to use AsyncPostFromString.  Even though I don't think caching of my GETs is occurring, EnTerr's comments got me thinking POST is really the way to go.  I'm still going to use the query string approach which requires no changes to my server PHP code.  In case anyone is wondering about the $_GET vs $_POST PHP superglobals and why no PHP code changes are needed to switch from GET to POST when using query strings, here's a good explanation of the two:  https://www.sitepoint.com/on-get-and-post/

Good read for me! This sentence summarizes it well:
"On $_GET and $_POST" wrote:
... The current names are confusing and obscures the intention of HTTP; More descriptive names would have been $_QUERY instead of $_GET and $_FORM* instead of $_POST (Which would match the etymology of the name $_FILES).

<sigh/> Leave it to PHP to muddle the matters!
But, PHP's behavior is a blessing in disguise for your case.

(^) Can we say these are 3 degrees of freedom?
0 Kudos
kjg
Visitor

Re: number of viewers query

This has been an education. All works very well. I appreciate all input.
Thanks again to belltown for the majic code!!
0 Kudos
morelsa33
Newbie

Re: number of viewers query

How can I integrate this scripts tin my local based website? I'm working for my Gclub program and I want to use this scripts for my website. 

0 Kudos
Need Assistance?
Welcome to the Roku Community! Feel free to search our Community for answers or post your question to get help.

Become a Roku Streaming Expert!

Share your expertise, help fellow streamers, and unlock exclusive rewards as part of the Roku Community. Learn more.