Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

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();
— asked October 31st 2010 by Chad Nantais
  • geolocation
  • loading
  • order
  • xhr
0 Comments

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()

    — answered October 31st 2010 by Stephane Pelamourgues
    permalink
    2 Comments
    • Thank you, Stephane. This worked.

      — commented October 31st 2010 by Chad Nantais
    • chad, make sure you mark this as the best answer so people who search the forums can see that!

      rocksteady,
      danno~

      — commented October 31st 2010 by danno watts
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.