Andrew
Andrew

Reputation: 4441

PHP / AJAX: Get web page content every 3 seconds until it changes

I have a web server (www.domain.com) that is pinging a subnet web server (test.domain.com) for displayed information until it changes. I want it to run this check every 3 seconds until the status changes to something besides the waiting message, then I want to display that information in the div.

I'm aware that I'll need AJAX to run this somehow if I want to load the page and then have this run as a script, but I've modified maybe 2 AJAX scripts in my life and have no clue where to go with this one.

The following code is my test base PHP that works for the basic workflow, but it does it all server side.

  $str = file_get_contents($url);
  $spanCount = preg_match_all("/\<span id\=\"spanId\"\>(.*?)\<\/span\>/",$str,$span);
  $spanString = implode($span[0]);
  echo "<div class='status' style='display:inline;'>";
  while($spanString == "<span id=\"spanId\">Waiting for stuffs...</span>"){
      echo "Waiting...";
      $str = file_get_contents($url);
      $spanCount = preg_match_all("/\<span id\=\"spanId\"\>(.*?)\<\/span\>/",$str,$span);
      $spanString = implode($span[0]);
      sleep(3);
  }
    if($spanString != "<span id=\"spanId\">Waiting for stuffs...</span>"){
      echo "<pre>";
      echo $spanString;
      echo "</pre>";
    }

  echo "</div>";

Upvotes: 2

Views: 338

Answers (1)

Andrew Tran
Andrew Tran

Reputation: 273

Does the AJAX call need to consume the entire HTML of the web page? If it's a service you control, allowing AJAX to make a GET to your php script and having it return a JSON object of data would make things very simple.

get to status.php returns -> {status:"waiting", content: null} //do nothing
get to status.php returns -> {status:"waiting", content: null} //do nothing
get to status.php returns -> {status:"someawesomestate", content: "<blink><marquee>You're our 1,000,000th visitor!</marquee></blink>"} // grab content and update page

Using JSONP will allow you very easily to grab the data cross domain if you have issues there. (jQuery powered example)

$.getJSON('the/path/status.php').
  .done(function(json) {
    if(json.status != "waiting") {
      $('.some-container').html(json.content);
    }
  })
  .fail(function( jqxhr, textStatus, error ) {
    alert('something exploded.');
});

Upvotes: 3

Related Questions