2

So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.

Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.

Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...

            <div id="current_song"></div>

            <script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
            <script language="javascript"> 
            {
              $.ajax({
                type: 'POST',
                url: 'script.php',
                data: 'getLatestInfo',
                dataType: 'json',
                cache: false,
              success : function(dp){
                $.getJSON('script.php', function(dp) {
            //'data' will be the json that is returned from the php file
                $.("#current_song").html("dp[9]");
            });
               getlatest();
              };
              });
            }
            </script> 

and here is the PHP parser

<?php 
Function getLatestInfo() {

$SERVER = 'http://chillstep.info:1984'; 
$STATS_FILE = '/status.xsl?mount=/test.mp3'; 
$LASTFM_API= '27c480add2ca34385099693a96586bd2'; 

//create a new curl resource 
$ch = curl_init(); 

//set url 
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE); 

//return as a string 
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 

//$output = our stauts.xsl file 
$output = curl_exec($ch); 

//close curl resource to free up system resources 
curl_close($ch); 

//loop through $ouput and sort into our different arrays 
$dp = array(); 

$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>"; 
$search_td = array('<td class="streamdata">','</td>'); 

if(preg_match_all("/$search_for/siU",$output,$matches)) { 
   foreach($matches[0] as $match) { 
      $to_push = str_replace($search_td,'',$match); 
      $to_push = trim($to_push); 
      array_push($dp,$to_push); 
   } 
} 
$x = explode(" - ",$dp[9]); 

echo json_encode($dp);
}
 ?>

I know it doesn't look pretty yet, but that's what CSS is for right?

Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jared Tritsch
  • 219
  • 2
  • 6

4 Answers4

1

Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.

to call the php function I suggest using jquery to perform an ajax call also to insert the data returned from the php, jquery is your best bet too.

mr_lewjam
  • 1,180
  • 1
  • 9
  • 20
  • okay. I think that's enough to get me going along that path. Ill read up on jquery and see what I come up with. I'll let you know if I run into trouble. – Jared Tritsch Oct 03 '12 at 11:08
  • great stuff, if your satisfied with the answer feel free to upvote or accept it :D – mr_lewjam Oct 03 '12 at 11:14
  • If Im returning an array, will it pull all of its component elements? Note in my original code I have all the data parsed out into individual array element under the Variable `@radio_info[]` can I write a jquery to pull the whole array at once, or will I need to query each element individually? – Jared Tritsch Oct 03 '12 at 11:17
  • firstly, you cannot 'write a jquery' (misleading name I know). JQuery is a hugely popular javascript library that provides very efficient ways of doing things such as requesting data from php files or modifiying html content. the data returned to the javascript is entirely decided by what your php function returns. you can have a separate php function for each variable, or you could have one function that returns an array. – mr_lewjam Oct 03 '12 at 11:24
  • okay I got it written out, and there aren't any PHP or script errors being thrown, but all the variables that JS uses are empty! I'm sure I'm missimg something stupid and obvious... – Jared Tritsch Oct 03 '12 at 16:59
  • Okay so what ime doing here is creating a JSON array at the end of the php script. I need ajax to run it, pull it, parse it out into those three variables, then paste "current_song" into its matching div. – Jared Tritsch Oct 04 '12 at 14:58
  • then you need a little bit of jquery code in your html, see the new answer I posted... – mr_lewjam Oct 04 '12 at 15:15
0

You need client side JavaScript for this. Get your hands on basic ajax books. You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript. The script will have to be new too, or this one edited to trace type of request and return data accordingly.

var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);

This is how you can check the response

req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText; 
//code to handle response
}
geekman
  • 2,224
  • 13
  • 17
  • I think I understand what you're saying. the reason I wrote the PHP that way is because Icecast, when metadata is requested through Curl (or any other HTTPRequest) it feeds back all the information in one massive string. The arrays I have are there to parse out the string into useful chunks. I'm not sure how I could use javascript to collect that data without having to parse it out in the client side script... unless I'm completely off base here, which is probably likely. – Jared Tritsch Oct 03 '12 at 10:49
  • Well arrays??? try your hands on JSON, to transfer data between your php and JavaScript. – geekman Oct 03 '12 at 10:50
  • :-/ I'm increasingly realizing that my chosen project to cut my teeth on these languages was more complex than I thought... I got more reading to do... JSON... interesting... – Jared Tritsch Oct 03 '12 at 10:57
  • comeon google it, its better than the old xml way, all you know XMLHttp is now JSONHttp :) – geekman Oct 03 '12 at 11:00
0

php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.

see the answer to this question

If you need any more detail let me know...

Community
  • 1
  • 1
mr_lewjam
  • 1,180
  • 1
  • 9
  • 20
  • Let me make sure I understand that link. I'm still new to javascript and PHP so forgive if I sound like a dolt. If I move the PHP into its own PHP document on the server, I can use ajax to call out individual variables from inside the script, such as `$radio_info['listeners']` and feed it back out into the page? If so, how do I ensure that the php document has the most up to date information to hand out? Does it re-run the script every time a variable is called for? – Jared Tritsch Oct 03 '12 at 10:44
0
    $.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});

look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly. Also dont forget to include the jquery library in your html header...

<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
mr_lewjam
  • 1,180
  • 1
  • 9
  • 20
  • Updated code into question, but its still not displaying anything on the finished document... the library is in the header. I just included it in the question where it was to show which library I was using. – Jared Tritsch Oct 04 '12 at 15:31
  • ok firstly...$.JSON is an alternative to $.ajax, dont use one inside the other.. also dont call the javascript function from inside itself, that is a receipe for disaster. call the function periodically from somewhere else. – mr_lewjam Oct 04 '12 at 15:42
  • also I think that the function name needs to go onto the end of the url ie script.php/getLatestinfo, and the data should be "{}"... thats all the help I can give you today, post your progress tomorrow if you are still stuck... – mr_lewjam Oct 04 '12 at 15:46