Mirakurun Mirakurun - 4 months ago 10
Javascript Question

Storing the value of variable in JS

Since my main language is C, I am used to pointers and I love them. Now I have some project which I need to finish in Javascript and I've got a problem which I don't know how to solve.

I want to store the value of a variable which I got from GET request. I have a script to send GET to PHP page, which then sends GET to my daemon written in C. When I get the string I wanted, I use

length
to measure the size of the string I got and in next GET request I want to send that number of bytes I got as the URL parameter.

window.onload = function() {
if (bytes === undefined) {
var bytes = 0;
}
var url = "/test/log.php?q=" + bytes;

function httpGet(url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.onload = function(e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log(xhttp.responseText);
var option = "";
obj = JSON.parse(xhttp.responseText);
for (var key in obj) {
option += obj[key];
}

document.getElementById("list").innerHTML = asdf;
bytes = option.length;
}
};
xhttp.onerror = function(e) {
console.error(xhttp.statusText);
}
};

xhttp.send();
}

var updateInterval = 2000;

function update() {
httpGet(url);
setTimeout(update, updateInterval);
}

update();
}


So, the focus is on the variable
bytes
. It should have the value 0 when the script is a first time called, and after every loop (it loops every 2 seconds, I didn't show the loop in the code) it should have the value of the previous length of received string.

Answer

You just need to make sure to add the bytes param onto your url in a way that changes with each call rather than just once at page load when it will always be 0.

window.onload = function() {
  if (bytes === undefined) {
    var bytes = 0;
  }
  var url = "/test/log.php?q=";

  function httpGet(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, true);
    xhttp.onload = function(e) {
      if (xhttp.readyState === 4) {
        if (xhttp.status === 200) {
          console.log(xhttp.responseText);
          var option = "";
          obj = JSON.parse(xhttp.responseText);
          for (var key in obj) {
            option += obj[key];
          }

          document.getElementById("list").innerHTML = asdf;
          bytes = option.length;
        }
      };
      xhttp.onerror = function(e) {
        console.error(xhttp.statusText);
      }
    };

    xhttp.send();
  }

  var updateInterval = 2000;

  function update() {
    httpGet(url + bytes);
    setTimeout(update, updateInterval);
  }

  update();
}