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?