Jed
Jed

Reputation: 1733

AJAX Variable Scope

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 

Upvotes: 1

Views: 195

Answers (3)

KooiInc
KooiInc

Reputation: 122936

If you want to use mlength from XHR outside the XHR callback, you'll have to wait until it has a value. You can do that using a timeout function:

var markers = []
   ,mlength = null
   ,showresult = function() { 
       if (mlength === null) { //=> no value, wait another 100 ms
        setTimeout(showresult,100);
       } else {                //=> there it is, alert it
        alert(mlength);
       }
     };

downloadUrl("phpsqlajax_genxml.php", function(data) {
    var xml = data.responseXML;
    markers = xml.documentElement.getElementsByTagName("marker");
    mlength = markers.length;
});

setTimeout(showresult,100);

Upvotes: 1

Roderick Obrist
Roderick Obrist

Reputation: 3828

Simple answer is no. I'm assuming that downloadUrl is asynchronous and you have no control over this (this means that alert happends before the callback that you provided).

If you really need to have the output ouside (I strongly strongly recomend against this). You could do this.

var markers=new Array();
var mlength=0;
var req = new XMLHttpRequest();
req.open("phpsqlajax_genxml.php", false);
req.send();
var xml = req.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
mlength = markers.length;
alert(mlength); //output is not 0 (ex. 3)

This is dirty dirty code though.

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

This is because AJAX, by definition, is asynchronous. By the time the alert is executed, the AJAX call hasn't returned yet. You need to move any code that is using mlength to 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.

Upvotes: 7

Related Questions