0

I need to do multiple XMLHttpRequest in short amount of time.

Before I used jquery and my code as the following and this worked well (I havent storring the results in any way):

function doStats(){

var postData....

$.ajax({
        url: url,
        type: 'post',
        data: postData,
        dataType: "json"
    }).done(function(response){

    
    }).fail(function(jqXHR, textStatus, errorThrown) {
   
    }); 

}

Now I have converted to javascript and if I call doStats multiple times in some short period, will this.responseText ensure my results are always correct and will creating xhrRequest_stat = new XMLHttpRequest(); not influence the one created before that?

function doStats(){

var params...

xhrRequest_stat = new XMLHttpRequest();
    xhrRequest_stat.onreadystatechange = function() {
        if (xhrRequest_stat.readyState == 4) {
            console.log(this.responseText)
        }
    }
    xhrRequest_stat.onerror = function(e) { 
        console.log('Error getStats: ' + e);
    };
    xhrRequest_stat.open('POST', url);
    xhrRequest_stat.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
    xhrRequest_stat.send(params);

 }

Because I call this funtion sometimes few times sometimes not, there is no real order to it, so I cant really use for loop.

Toniq
  • 4,492
  • 12
  • 50
  • 109
  • 1
    Where is `xhrRequest_stat` declared? Make sure you get the [scope](/q/500431/4642212) right. See also [What is the purpose of the var keyword and when should I use it (or omit it)?](/q/1470488/4642212). – Sebastian Simon Nov 27 '22 at 09:42
  • Using `this` should work (like in `this.responseText`), but also make sure that `xhrRequest_stat` is declared *inside* of the function, then you can also access the request object by that variable in the event handlers (like in `xhrRequest_stat.readyState`). – Bergi Nov 27 '22 at 11:10
  • It was global but I realize now I need to declare it local inside function if I want to make this work. – Toniq Nov 27 '22 at 15:40

1 Answers1

0

You must add the "const" keyword when you declare/init your xhrRequest_stat variable. In this way, you will be sure that each time you call the function you create a new xhrRequest_stat variable.

If you want to avoid side effects in JavaScript, the variables used in your function must be in the signature of the function (url, here) :

function doStats(url){

var params...

const xhrRequest_stat = new XMLHttpRequest();
    xhrRequest_stat.onreadystatechange = function() {
        if (xhrRequest_stat.readyState == 4) {
            console.log(this.responseText)
        }
    }
    xhrRequest_stat.onerror = function(e) { 
        console.log('Error getStats: ' + e);
    };
    xhrRequest_stat.open('POST', url);
    xhrRequest_stat.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
    xhrRequest_stat.send(params);

 }
Ian R.
  • 26
  • 2