dpi dpi - 3 months ago 24
Javascript Question

AJAX callback return value handling in jQuery

I have this simple function that fetches gis data from mapquest:

function reverseGeocoding(lat,lng){
var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
$.ajax({
url: url,
crossDomain:true,
success: function(response){
$("#revgeo-place").html(response.display_name);
}
});

}


How can I improve it so that when this function is called from another function the return value is updated asynchronously?

I don't want to explicitly put any DOM reference in the function, and I want to keep the ajax asynchronous, ideally should be something like this:

$("#revgeo-place").html(reverseGeocoding(lat,lng).display_name);

function reverseGeocoding(lat,lng){
var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
$.ajax({
url: url,
crossDomain:true,
success: function(response){
console.log(response);
return response;
}
});

}


It looks that when I do this the DOM object does not update, and after then the function returns the response.

Any ideas would be helpful thanks!

Answer

You may use a callback:

function reverseGeocoding(lat,lng, callback){
    var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
    $.ajax({
        url: url,                       
        crossDomain: true,
        success: callback
    });
};

reverseGeocoding(lat,lng, function(response){

    $("#revgeo-place").html(response.display_name);

});

So your reverseGeocoding function is agnostic to DOM.

Comments