Search code examples
javascriptprototypejsglobal-scope

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


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


Solution

  • 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.