0

I'm trying to return the result from an AJAX rest response in a function. When I use the following code, the result i get from the alert is 0 which is what I initialized. Is it returning the result before the response comes back? If so is there a way to wait until the response has finished to return the result?

$(document).ready(function() {
    var newcoord = setCoordinates();
    alert(newcoord.lat);

    function setCoordinates(){
        var latlong = {lat: 0, ltd: 0};
        $.ajax({
            url: "https://api.wheretheiss.at/v1/satellites/25544"
        }).then(function(data) {
            latlong.lat = data.latitude;
            latlong.ltd = data.longitude;
        });

        return latlong;
    }
});
mattc19
  • 678
  • 1
  • 11
  • 23

1 Answers1

1

That won't work for sure since your function will return before ajax call ended. This could do the trick according what you show:

$(document).ready(function() {
    var ajaxCall = setCoordinates();

    ajaxCall.done(function(data) {
        alert(data.lat);
    });

    function setCoordinates(){
        return $.ajax({
            url: "https://api.wheretheiss.at/v1/satellites/25544"
        });
    }
});
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155