1
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

Rob W
  • 341,306
  • 83
  • 791
  • 678
TigerTiger
  • 10,590
  • 15
  • 57
  • 72

2 Answers2

5

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
  • 339,989
  • 67
  • 413
  • 406
  • @Wbdvlpr - Put whatever you want to to happen upon completion of the call within the onComplete method, instead of after the Ajax.Request. – karim79 Aug 17 '09 at 13:54
  • 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. – TigerTiger Aug 17 '09 at 13:58
2

"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).

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
cletus
  • 616,129
  • 168
  • 910
  • 942