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&
Solution 1:
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.
Solution 2:
Return the deferred object from the ajax call, and use the done()
function to update the HTML when the ajax call is done :
reverseGeocoding(lat,lng).done(function(data) {
$("#revgeo-place").html(data.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';
return $.ajax({
url: url,
crossDomain:true
});
}
Solution 3:
Your second example doesn't work because the value of the AJAX request has not returned when you set the value of $("#revgeo-place").html()
.
If you are looking to be able to amend the element which is updated, add it as a parameter to your function like this:
function reverseGeocoding(lat, lng, $updateElement){
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){
$updateElement.html(response.display_name);
}
});
}
reverseGeocoding(latitude, longitude, $("#revgeo-place"));
Solution 4:
You could add a onSuccess
parameter to the reverseGeocoding
function that is called when the ajax function completes
function reverseGeocoding(lat, lng, onSuccess){
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){
onSuccess();
}
});
}
function onReverseGeocodingSuccess() {
$("#revgeo-place").html(response.display_name);
}
reverseGeocoding(100, 200, onReverseGeocodingSuccess);
Post a Comment for "AJAX Callback Return Value Handling In JQuery"