How to append text to a variable, within a function, in Javascript?

429 Views Asked by At
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

2

There are 2 best solutions below

2
karim79 On BEST ANSWER

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.

2
cletus On

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