I am calling a function to refresh a part of the current page with a jQuery.post - and then after that function completes I need to execute another function that updates the Google Map on that page, using the updated HTML written out from the $.post
I cannot nest the functions because DoGoogleMap() won't work within the scope of the RefreshSubdivisionList() function.
How do I make it wait for the $.post to finish writing the updated HTML to the page before it calls the DoGoogleMap() function?
function RefreshSubdivisionList() {
var formActionScript = jQuery("#RefreshSubdivisionForm").attr('action');
jQuery.post(formActionScript, jQuery("#RefreshSubdivisionForm").serialize()).done(function(data) {
jQuery(".subdivision-list").html(data).show();
}, 'text');
return true;
}
jQuery("#RefreshSubdivisionForm").submit(function(event) {
event.preventDefault();
jQuery.when( RefreshSubdivisionList() ).done(function(){
jQuery('#map_canvas').gmap('destroy');
DoGoogleMap();
});
return false;
});
jQuery.when() provides mechanisms to deal with the case of synchronizing multiple async calls. Take a look:
function ajax1 {
return $.ajax("/page1/action", {});
}
function ajax2 {
return $.ajax("/page2/action", {});
}
var promise = $.when(ajax1, ajax2);
promise.done(function (resp1, resp2) {
// The parameters resp1 and resp2 are the responses
// of their respective ajax1 and ajax2 calls.
// Each parameter is an array that contains the ajax response
// with the following signature:
// [data, statusText, jqXHR]
// See: http://api.jquery.com/jquery.ajax/#jqXHR
// suppose the data response for ajax1 is: "Hello"
// suppose the data response for ajax2 is: "world"
var data = resp1[0] + " " + resp2[0];
if ((/hello\sworld/i).test(data)) {
console.info("Promises rules!");
}
});
In the previous example we handle success responses, but in the same way we can handle failure responses.
The jqXHR object returned by jQuery.ajax() implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information)
Other way is to create deferred objects, and resolve each deferred object with the expected result and finally, unify the resolved responses:
var d1 = $.Deferred();
var d2 = $.Deferred();
$.when(d1, d2).done(function (resp1, resp2) {
console.log(resp1); // "Fish"
console.log(resp2); // "Pizza"
});
d1.resolve("Fish");
d2.resolve("Pizza");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With