Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery deferred object example using AJAX
jQuery(document).ready(function($) {
$('#myButton').click(function(event) {
event.preventDefault();
var id = $('#someInput').val();
callEndpoint(id).done(function(data) {
// Do something with the response
}).fail(function(jqXHR, textStatus, errorThrown) {
// Show error message
});
});
});
function callEndpoint(id) {
var deferredObject = $.Deferred();
$.ajax({
type: "GET",
url: "/get/banana/by/" + id
}).done(function(response) {
if (response.status !== "success") {
deferredObject.reject(response.message);
return false;
}
deferredObject.resolve(response.data);
return true;
}).fail(function(jqXHR, textStatus, errorThrown) {
var errorMessage = "Request Failed (server response logged to console): " + textStatus + ", " + errorThrown + ". Server response: " + jqXHR.responseText;
deferredObject.reject(errorMessage);
});
return deferredObject.promise();
}
// You can also do something like this:
function callEndpoint(id) {
return $.ajax({
type: "GET",
url: "/get/banana/by/" + id
});
}
callEndpoint(12).done(function(data) {
// Handle success
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle fail
});
// Or, you can use $.when()
$.when(callEndpoint(12)).done(function(response) {
// Handle the response here
});
// $.when() can also handle multiple functions:
function callAnotherEndpoint() {
return $.ajax({
type: "GET",
url: "/another/endpoint"
});
}
$.when(callEndpoint(12), callAnotherEndpoint()).done(function(endpointResponse, anotherEndpointResponse) {
// Handle the response here.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.