Here is a program that calls ajax to read a value from the header of a http response and set a variable called _ecpop and use that for later operations…
So I defined a variable globally called _ecpop as
var _ecpop="";
and then here is the ajax call code:
if (typeof XMLHttpRequest != "undefined") {
_ec_req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
_ec_req = new ActiveXObject("Microsoft.XMLHTTP");
}
// make the request
_ec_req.open("GET", requestString, true);
// function to deal with response
_ec_req.onreadystatechange = function() {
if (_ec_req.readyState==4)
{
if (_ec_req.status==200)
{
var respHeaders = _ec_req.getAllResponseHeaders();
// strip out unnecessary headers
respHeaders = respHeaders.replace (/\n/g,"|X|");
var beg = respHeaders.indexOf("ECAcc (");
_ecpop = respHeaders.substring(beg+7,beg+10);
//make an if statement here...
console.log(_ecpop);
}
}
}
console.log(_ecpop);
and the rest of the code uses _ecpop.
The problem is the browser executes the rest of the code with _ecpop=””. i.e. first the second console.log(_ecpop); returns empty and then the first console.log(_ecpop); returns the correct value.
Is there anybody who knows how I can get around it? it is so irritating …
Thanks,
Amir.
AJAX (an acronym for Asyncronous Javascript And XML) is inherently asynchronous. That means that it begins executing when the Javascript engine encounters it in a script, but the rest of the script continues processing without waiting for the AJAX call to complete.
You can circumvent this behavior by instructing your AJAX call to operate synchronously:
Setting
falseas third parameter ofopen()will provide your requested behavior.