cameron213
cameron213

Reputation: 169

AJAX with callback functions

I am having trouble access data within an ajax connection. Not sure what is wrong with my code. It seems as though it never reaches the 2nd function. Any ideas?

function fetchgps(callback)
{
  var url = "http://www.instamapper.com/api?action=getPositions&key=584014439054448247";

  var myRequest = new XMLHttpRequest();
  myRequest.onload = function(e) {xml_loaded(e, myRequest, callback);}
  myRequest.open("GET", url);
  myRequest.setRequestHeader("Cache-Control", "no-cache");
  myRequest.setRequestHeader("wx", "385");
 myRequest.send(null);

 return myRequest;
}

function xml_loaded(event, request, callback)
{
 if (request.responseText){
  var obj = {error:false, errorString:null}

   var data = myRequest.responseText;
   collected=data.split(",");   //parses the data delimited by comma and put data into array

obj.latitude = collected[4];
obj.longitude = collected[5];

callback(obj);
  }

  else
{
callback ({error:true, errorString:"XML request failed. no responseXML"}); //Could be any number of things..
}

}

function dealwithgps(obj)
{
lat = obj.latitude;
lon = obj.longitude;
document.write(lon);
document.write(lat);
}

fetchgps(dealwithgps);

Upvotes: 2

Views: 410

Answers (1)

naikus
naikus

Reputation: 24472

Thats request.onreadystatechange instead of request.onload

function fetchgps(callback)
{
  var url = 
   "http://www.instamapper.com/api?action=getPositions&key=584014439054448247";

  var myRequest = new XMLHttpRequest();
  // myRequest.onload = function(e) {xml_loaded(e, myRequest, callback);}
  myRequest.onraedystatechange = function() { //onraedystatechange instead of onload!!
    xml_loaded(myRequest, callback);
  }
  myRequest.open("GET", url);
  myRequest.setRequestHeader("Cache-Control", "no-cache");
  myRequest.setRequestHeader("wx", "385");
 myRequest.send(null);

 return myRequest;
}

function xml_loaded(request, callback) {
   if(request.readyState === 4) {
       //... only then do your processing
   }
}

Upvotes: 3

Related Questions