javascript - Only last of multiple ajax requests gets completed -


i'm trying create script allows me make ajax call few lines of code. script works 1 ajax request, when comes handling multiple request @ once fails. have done wrong ?

the code processes last request, while leaving others "loading ...".

here's code:

/****************   related javascript inside html document ****************/ // first request var ajax1 = new ajax_class(); ajax1.meth = "get"; ajax1.file = "ajax_info.txt"; ajax1.elem = "results"; ajax1.send = null; ajax1.ajax_call(ajax1.meth, ajax1.file, ajax1.elem, ajax1.send);  ...  // third request var ajax3 = new ajax_class(); ajax3.meth = "get"; ajax3.file = "ajax_info3.txt"; ajax3.elem = "results3"; ajax3.send = null; ajax3.ajax_call(ajax3.meth, ajax3.file, ajax3.elem, ajax3.send);  /****************   related html inside html document ****************/  <body> <div id="results">nothing has happend yet 1....</div> <div id="results2">nothing has happend yet 2 ....</div> <div id="results3">nothing has happend yet 3 ....</div> </body>   /****************   related code inside javascript document ****************/  function ajax_class () {  this.meth = "get"; this.file; this.elem; this.send = null;  this.ajax_call = function (meth, file, elem, send) {     x = new xmlhttprequest();     x.onreadystatechange = function () {         if (x.readystate == 4 && x.status == 200) {            _id(elem).innerhtml = x.responsetext;         }         else {             _id(elem).innerhtml = "loading ...";         }     }     x.open(meth , file, true);     x.send(send); } } 

works now, had add "var" in front of x variable

it's @ least partially because each new xmlhttprequest being set same global x, can keep 1 of them. means later references x.readstate , x.responsetext aren't referring "correct" instance.

you'll want declare x when or before setting it's scoped , unique each ajax request:

var x = new xmlhttprequest(); 

for more info, see difference between using var , not using var in javascript.


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -