strakz strakz - 10 days ago 7
PHP Question

Javascript setInterval method return always the same result from PHP method but I need changed data

So my problem is that I need to update some data from other site, and for calling that data I have php function where is the URL as parameter. ..So in JS I create a function that is in cycle with setInterval where I call that php function with URL parameter where are data stored, but it always return the same data..(data is actually playing track on stream, so data changed every +- 3 minutes) Data changes only on refresh page (f5) ..but I need update that data in background ..

this is the PHP function

function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
$data = str_replace(",,","},",$data);
$data = str_replace("}}]}}","}]}}",$data);
$data = str_replace("]}}","}]}}",$data);
$data = str_replace(",}}","}}}",$data);
$data = str_replace("}}]}}","}]}}",$data);
return $data;


In js I call in setInterval cycle only console.log to show result of php function..

console.log(<?php echo (get_content("http://server1.internetoveradio.sk:8809/status-json.xsl"));?>["icestats"]["source"])

Answer

Well, yeah. The PHP only gets called once in this case, the one time you echo out the contents of get_content();

If you want to get the content over and over again, use XmlHTTPRequest to call a PHP file which then returns the the result of get_content();

jQuery implements ajax ( XmlHTTPRequest ) to do exactly that.

jQuery.ajax({
   url: "http://path.to/your_script.php",
   method: "get",
   complete: function( response ){
      console.log(response);
   }
});

edit: Create a new .php file and paste this:

<?php

function get_content($URL){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $URL);
  $data = curl_exec($ch);
  curl_close($ch);
  $data = str_replace(",,","},",$data);
  $data = str_replace("}}]}}","}]}}",$data);
  $data = str_replace("]}}","}]}}",$data);
  $data = str_replace(",}}","}}}",$data);
  $data = str_replace("}}]}}","}]}}",$data);
  return $data;
}

echo get_content("http://server1.internetoveradio.sk:8809/status-json.xsl");

In your html, add this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
    jQuery(document).ready(function(){
    jQuery.ajax({
       url: "http://path.to/your_script.php",
       method: "get",
       complete: function( response ){
           console.log(response);
       }
    });
    });
</script>

This is the most rudimentory version, but it should point you in the right direction hopefully.