whenever i try to run something like the following, firebug tells me that "markers is undefined" at the line "for (var i=0 …"
but i declared markers as a global variable at the top right…?
var markers;
function load() {
$.get("phpsqlajax_genxml.php", function(data) {
markers = data.documentElement.getElementsByTagName("marker");
});
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name")
//do more stuff
}
}
but when i do this, it works.
var markers; function load() { $.get("phpsqlajax_genxml.php", function(data) { markers = data.documentElement.getElementsByTagName("marker"); makeMarkersWithXMLinfo(); }); function makeMarkersWithXMLinfo() { for (var i = 0; i < markers.length; i++) { var name = markers[i].getAttribute("name") //do more stuff } } }
i’m not even passing "markers" as an argument to my makeMarkersWithXMLinfo() function. but yet it works. what’s going on? thnx
The problem you’re having is that
getstarts an asynchronous operation. So your code immediately following the call togethappens before the success callback on thegetis run. E.g. (see the comments):Your second example is the correct way to code it (although I’d recommend avoiding a global entirely), because you’re using
markersonly after the GET has completed.