0

I am doing something like that:

var globals = {
   variable: undefined
};
function Tools() { }
Tools.ajax = function() {
        var xmlhttp;
        return {
            createXmlhttp: function() {
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                } else {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
            },
            onreadystatechange: function(action) {
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                        action(xmlhttp.responseText);
                    }
                };
            },
            execute: function(action, url, data) {
                this.createXmlhttp();
                this.onreadystatechange(action);
                xmlhttp.open("POST", url, true);
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xmlhttp.send(data);
            }
        };
    };
    Tools.getFromApi = function(fooBar) {
        var url = "http://some_url.com/ajax_request.php";
        var data = "fooBar=" + fooBar;

        this.ajax().execute(function(responseText) {
            globals.variable = responseText;
        }, url, data);
    };

And then I am calling this method from different function, and want to alert the content of globals.variable:

function anotherFunction() {
   Tools.getFromApi("aaa");
   alert(globals.variable);
}

The problem is that my variable is empty here, because ajax has not yet got the response. Some sort of sleep function before alert would probably solve the issue, but then again, there's no sleep function in JS, and I wouldn't know how long to sleep.

How can I solve this?

khernik
  • 2,059
  • 2
  • 26
  • 51

1 Answers1

0

This is happening since the ajax call is async.

One way to correct this is by passing the callback into your function and invoking it after you have the response:

Tools.getFromApi = function (fooBar, callback) {
    var url = "http://some_url.com/ajax_request.php";
    var data = "fooBar=" + fooBar;

    this.ajax().execute(function (responseText) {
        globals.variable = responseText;
        callback();
    }, url, data);
};


Tools.getFromApi("aaa", function(){
    alert(globals.variable);
});

Here's a sample JSFIDDLE.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99