Forum Moderators: open

Message Too Old, No Replies

global variable problem

global variable problem ajax

         

dmdickie

1:37 pm on Jan 24, 2011 (gmt 0)

10+ Year Member



Hi

I am struggling! why would this would not work. I am a beginner.

The global variable 'birds' array populates from an xml file in processResponse_autosuggest, though I think for some reason it is treating birds as a local variable within this function because when I try to access birds after this function is called and finished, birds.length is zero though calling birds after populating within the function gives array of length 21 which is what I expect.

thanks for looking
dickie



//<!--
var asyncRequest_autosuggest;
var birds = new Array();

function processResponse_autosuggest() {
if (asyncRequest_autosuggest.readyState == 4 && asyncRequest_autosuggest.status == 200 && asyncRequest_autosuggest.responseXML) {
var birdsxml = asyncRequest_autosuggest.responseXML.getElementsByTagName("bird");
for (var i=0; i < birdsxml.length; i++) {
birds[i] = birdsxml.item(i).firstChild.nodeValue;
}
alert(birds.length) //returns 21. expected
}
}

function getautosuggest(id) {
var userInput = document.getElementById(id).value;
getArrayBirds('birds.xml');
alert(birds.length); // returns zero. don't know why
}

function getArrayBirds(url) {
try {
asyncRequest_autosuggest = new XMLHttpRequest();
asyncRequest_autosuggest.onreadystatechange = function() {processResponse_autosuggest()};
asyncRequest_autosuggest.open('GET', url, true);
asyncRequest_autosuggest.send(null);

}
catch (exception) {
alert('Request Failed');
}
}



//-->

</script>
</head>
<body>
<form>
<input id="autosuggestinput_id" onkeyup="getautosuggest(this.id)" />
</form>
</body>
</html>

Fotiman

2:03 pm on Jan 24, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The reason this isn't doing what you expect is because the AJAX request is asynchronous. Here's what happens:

1. getautosuggest is called
2. getArrayBirds is called
3. a new XMLHttpRequest is created and a request is sent. At this point, because the request is asyncronous, getArrayBirds continues execution (there is nothing to execute after the send request, so getArrayBirds returns normally)
4. getautosuggest tries to alert the birds array length and gets zero because the XMLHttpRequest hasn't gotten and processed the response yet.
5. At some point after this, the response comes back from the server and processResponse_autosuggest is called.

dmdickie

2:40 pm on Jan 24, 2011 (gmt 0)

10+ Year Member



thanks fotiman .. a beginner's mistake eh!
thanks for your time .. of course it opens up a new can of worms .. the fun of it all ;-) dickie