Is there a way to output desired mlength outside downloadURL() in the code below? How?
var markers=new Array();
var mlength=0;
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
mlength = markers.length;
alert(mlength); //output is not 0 (ex. 3)
});
alert(mlength); //outputs 0
This is because AJAX, by definition, is asynchronous. By the time the
alertis executed, the AJAX call hasn’t returned yet. You need to move any code that is usingmlengthto inside the success callback.The other option is to make the AJAX request synchronous, but that’s usually not what you want as it tends to lock up the browser until a response is received.