Murlidhar Fichadia Murlidhar Fichadia - 3 months ago 10
PHP Question

Api Call Ajax n seconds GET request

The API shows live values and changes very frequently, so I am trying to make a call every second and show it to the webpage.

I tried a get request call every N seconds using

set_interval()
but the values load only once and don't make a call again.

<p id="val"></p>
<p id="val2"></p>
<p id="val3"></p>

<script>
var xhttp = new window.XMLHttpRequest();
xhttp.open("GET", "http_url_link", true);
xhttp.send();
xhttp.onreadystatechange = myFunction(xhttp);

function myFunction() {
if (xhttp.readyState == 4) {
var xmlDoc = xhttp.responseXML;
var val1= xmlDoc.getElementsByTagName('value_1')[0].childNodes[0];
var val2 = xmlDoc.getElementsByTagName('value_2')[0].childNodes[0];
var val3 = xmlDoc.getElementsByTagName('value_3')[0].childNodes[0];
document.getElementById('val3').innerHTML =
v3.nodeValue;
document.getElementById('val').innerHTML =
v1.nodeValue;
document.getElementById('val2').innerHTML =
v2.nodeValue;
}
}
myFunction();
setInterval(myFunction, (1000));
</script>

Answer

var xhttp = new window.XMLHttpRequest();

here xhttp object create once when the script is running And you get proper output for one time. So you need to call this after 1 second.

function myFunction() {
   var xhttp = new window.XMLHttpRequest();
   xhttp.open("GET", "http_url_link", true);
   xhttp.send();
   xhttp.onreadystatechange = function(){
      if (xhttp.readyState == 4) {
       var xmlDoc = xhttp.responseXML;
       var val1=xmlDoc.getElementsByTagName('value_1'[0].childNodes[0];
       var val2 = xmlDoc.getElementsByTagName('value_2')[0].childNodes[0];
       var val3 = xmlDoc.getElementsByTagName('value_3')[0].childNodes[0];
       document.getElementById('val3').innerHTML=v3.nodeValue;
       document.getElementById('val').innerHTML=v1.nodeValue;
       document.getElementById('val2').innerHTML=v2.nodeValue;
    }
  }

setInterval(myFunction,(2000));

Happy coding :)

Comments