views:

172

answers:

2
var err = '';

err += 'err a';
myString = 'Blah';
new Ajax.Request('/check_me.php',
 {
  method:'get',
  parameters: {
    'string': myString
   },
   evalScripts: true,
   onComplete: function(t){
    var response = t.responseText;
    if (response == false) {
     //do nothing
    } else {
     err += 'err b.\n';
     //alert(err);
    }
   }
  });

err+= 'err c';

alert(err);

In the above, it should alert "err a" + "err b" + "err c". But I just get "err a" + "err c". If I try to alert(err) with in oncomplete, then I can see the text being appended to whatever values it has earlier. In this case, "err a" + "err b". If I close this alert box, the final alert box, just displays a and c.

So it is reading value from a global variable but not writing to it.

How do get it working i.e. set it to "b" as well??

Thanks

+5  A: 

Ajax requests happen asynchronously, so the execution of the Javascript on your page will continue after your ajax call has been dispatched, irrespective of whether or not the response has been returned.

So when your script alerts the err variable, the output you get is not what you expect because onComplete has not yet been called.

karim79
so how do I get that working?
Wbdvlpr
@Wbdvlpr - Put whatever you want to to happen upon completion of the call within the onComplete method, instead of after the Ajax.Request.
karim79
any ideas how do I track when oncomplete ends?? Just fyi.. if I alert within the oncomplete function, then this alert box pops up before the final one does.
Wbdvlpr
+2  A: 

"err a err c err b" is the correct output. The order is:

  • append "err a";
  • create a new AjaxRequest, which starts the request (asynchronous)
  • append "err c"
  • AjaxRequest complete happens appending "err b"

You need to either make the request synchronous (not recommended) or move the append of "err c" to within the complete method (like "err b" is).

cletus
does this mean the final alert(err) shoule print in the order as stated by you above? It doesnt.
Wbdvlpr
just fyi .. order of output doesnt matter to me
Wbdvlpr