0

I have an xml with some information(names) wich I want to use in javascript and I want them in an array so I can use it later in diferent ways, but so far I just have been able to print it from inside the function(In the second alert), but not outside of it(in the first alert).

I would like to now why in this case I cant use a global variable and how can I manage to get the information in a gloval array so I can use it later.

 var team = [];
 var xmlhttp = new XMLHttpRequest();
 xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      team = myFunction(this);
      /*2º alert*/
      alert(team);
    }
 };

 xmlhttp.open("GET", "team.xml", true);
 xmlhttp.send();

 function myFunction(xml) {
  var x, i, xmlDoc;
  xmlDoc = xml.responseXML;
  var txt = [];
  x = xmlDoc.getElementsByTagName("name");
  for (i = 0; i< x.length; i++) {
    txt.push(x[i].childNodes[0].nodeValue);
  }
  return txt;  
}
/*1º alert*/
alert(team);

Thanks.

  • The first `alert()` is running immediately after you instantiate the XHR and the data hasn't come back yet. The second one is in your success callback and has waited for the XHR to complete. JavaScript code doesn't necessarily process in the order that it is written. – Scott Marcus Mar 16 '18 at 13:48
  • Thanks, I kind of understand it, I have put made a function that executes when I press a buttom and because It is executed after my code now it haves the result and it shows it in the right way. Thanks for the help. – William Slim Mar 16 '18 at 14:14

0 Answers0