views:

40

answers:

1

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);
+2  A: 

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
   }
}
naikus
Tried that already...I get an error from the browser...."The data necessary to complete that operation is not yet available"
cameron213
You will have to chech for myRequest.readystate and only do processing when the ready state is 4. Check my answer.
naikus
cameron213
Appears to be a scope issue...i tested by adding the following line below the readyState statement. /alert(request.responseText);I get back the alert message. Any ideas?
cameron213
cameron213
Why not use jQuery? Also, use [JSLint](http://www.jslint.com/) to catch stuff like that.
Andy Atkinson