filip.karas
filip.karas

Reputation: 598

Simultaneous ajax calls

I'm trying to make 2 (or more) ajax calls simultaneously. I don't want to use jQuery, only pure JavaScript.

Most of the time, it works. data1 will output data from sample.com/ajax1 and data2 will output data from sample.com/ajax2, but sometimes (1 from 10) the second AJAX call will display result from the first one.

Why is this happening? Both AJAX requests are requesting data from the same domain, but from different URLs. Is there any way how to prevent this behavior?

Here is the script:

// First AJAX
var xmlhttp1;

// Second AJAX
var xmlhttp2;

if (window.XMLHttpRequest) {
    xmlhttp1 = new XMLHttpRequest();
} else {
    xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp1.onreadystatechange = function() {
    if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
        data = JSON.parse(xmlhttp1.responseText);
        console.log('data1: ' + data);
    }
}

xmlhttp1.open("GET", "http://sample.com/ajax1", true);
xmlhttp1.send();

if (window.XMLHttpRequest) {
    xmlhttp2 = new XMLHttpRequest();
} else {
    xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp2.onreadystatechange = function() {
    if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
        data = JSON.parse(xmlhttp2.responseText);
        console.log('data2: ' + data);
    }
}

xmlhttp2.open("GET", "http://sample.com/ajax2", true);
xmlhttp2.send();

Upvotes: 0

Views: 2654

Answers (3)

cocco
cocco

Reputation: 16706

The problem is probably because you forgot to define data inside your function

anyway with this function you can create multiple requests and have more control over them..

var req={};
function ajax(a){
 var i=Date.now()+((Math.random()*1000)>>0);
 req[i]=new XMLHttpRequest;
 req[i].i=i;
 req[i].open('GET',a);
 req[i].onload=LOG;
 req[i].send();
}
function LOG(){
 console.log(this.i,this.response);
 delete req[this.i];//clear
}
window.onload=function(){
 ajax('1.html');
 ajax('2.html');
 ajax('3.html');
}

uses xhr2... you need to modify the code to make it work with older browsers.

Upvotes: 0

Jedediah
Jedediah

Reputation: 1944

Because you're not properly encapsulating data. The way you have it written, data is a global object, so it's available to be modified by either ajax call. Since ajax calls are asynchronous, this will lead to unpredictable values for data.

Upvotes: 1

mati
mati

Reputation: 5348

First of all, I recomment wrapping your xmlHttpRequest generation/handling in a function, so you don't duplicate code that much.

The problem you have there is that the data variable is global, so both ajax callbacks are using the same variable. You can fix it using the var keyword in both calls.

xmlhttp2.onreadystatechange = function() {
    if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
        var data = JSON.parse(xmlhttp2.responseText);
        console.log('data2: ' + data);
    }
}

Upvotes: 1

Related Questions