1

I make an Ajax request to an API and get back an array but want to use it outside function, all as a global variable.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
  }
};

xhttp.open("GET", url, true);
xhttp.send();
var latitudes = [];

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  var records = xmlDoc.firstChild.children[2].children;

  var resultLat
  var arrayLat = [];
  latitudes = arrayLat;
  var i
  for (i = 0; i < records.length; i++) {
    resultLat.push(records[i].children[6].innerHTML);
  }

  arrayLat = resultLat.filter(function(record) {
    return record != "Kulturlämning";
  });
  //Works
  console.log(arrayLat);
  latitudes = [arrayLat];
}
//Empty
console.log(latitudes);
  • The url to the API var url = "http://kulturarvsdata.se/ksamsok/api?method=search&x-api=%220TpGFFHFERF2Em9yXlBc%22&query=item=%22runsten%22and%20itemType=%22kulturlämning%22and%20 itemName=%22runristning%22%20and%20geoDataExists=j+and+place=%22Järfälla%22&recordSchema=xml&fields=itemName,itemDescription,itemType,lon,lat,hasImage,thumbnail"; – Ernesto Segovia Nov 13 '18 at 19:23
  • You are logging `latitudes` before the ajax request has finished. Ajax requests are asynchronous. –  Nov 13 '18 at 19:24
  • Aaaa of course thanks – Ernesto Segovia Nov 14 '18 at 10:58

0 Answers0