xhr sending before getCurrentPosition completes
I am having an issue with the following code. UpdateLocation does not set the position properties in time for xhr.send and the xhr request gets sent with null values for latitude and longitude.
How can I hold back the sending of the xhr until I get the location data from UpdateLocation?
var Props = Ti.App.Properties;
// create table view data object
var currentData = [];
var returnedData;
function UpdateLocation() {
Ti.Geolocation.getCurrentPosition(function(e)
{
Ti.API.info("received geo response");
if (e.error)
{
alert(e.error);
return;
}
var longitude = e.coords.longitude;
var latitude = e.coords.latitude;
Ti.App.Properties.setDouble('Latitude',latitude);
Ti.App.Properties.setDouble('Longitude',longitude);
});
}
function doAjaxRequest() {
UpdateLocation();
var xhr = Ti.Network.createHTTPClient();
xhr.setTimeout(30000);
var thisUUID = Ti.Platform.id;
var latitude = Props.getDouble('Latitude');
var longitude = Props.getDouble('Longitude');
if (latitude) {
xhr.open('GET','http://mydomain.com/myResponder.php?sUUID='+thisUUID+'&Latitude='+latitude+'&Longitude='+longitude);
xhr.onload = function ()
{
returnedData = this.responseText;
var rDataJSON = JSON.parse(returnedData);
doSomethingWithData(rDataJSON);
};
xhr.onerror = function(e) {
Ti.API.info('GET returned error:' + e.error);
};
xhr.send();
} else {
alert('location was not updated in time for xhr.send');
}
}
doAjaxRequest();
1 Answer
-
did you try to call first UpdateLocation() (instead of doAjaxRequest() at the last line of your code)
and at the end of your UpdateLocation() function calling doAjaxRequest()
and of course remove the UpdateLocation(); first line of function doAjaxRequest()