简体   繁体   中英

Update variable sent to ajax call with value from previous ajax response

I have an ajax function that executes every 3 seconds, calling a 'file2.php' file. I pass a variable $lastid through POST, use it in 'file2.php' and then in the response i get a new last id, wich I need to send as $lastid the next time the ajax function executes. But I can't find a way to update the variable that actually replaces the previous value in the ajax call.

I have tried assigning response.lastid to var lastid inside the ajax function but it doesn't help. I keep getting the same response i got in the previous call, eternally.

This is the ajax function and how I set the variable initially

<script>
var lastid = <?php echo $lastid; ?>;

function nuevospedidos() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "file2.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = JSON.parse(this.responseText);
      console.log(response);
      var lastid = response.lastid;
    }
  };
  xhttp.send("lastid=" + lastid);

}
setInterval(nuevospedidos, 3000);
</script>

The response i get is this json object

{lastid: "4074",
contenido: "some content",
originalid: "4073"}

I would like to receive that response only once, and then update the lastid variable with the lastid that the json object brings, so that the next time it executes it knows that was the last id processed.

This is a scope issue. Your lastid variable is not global when declared inside a function .

You must declare it as a global variable:

var lastid = <?php echo $lastid ?>;
function newId() {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "file2.php", true);
    xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var response = JSON.parse(this.responseText);
            lastid = response.lastid;
        }
    };
    xhttp.send("lastid=" + encodeURIComponent(lastid));
}
setInterval(newId, 3000);

You can use the window object to specify that you are accessing the global variable

window.lastid = response.lastid;

As explained here: How to reference a global scope variable into the local scope?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM