Skip to content

Instantly share code, notes, and snippets.

@Server4001
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Server4001/09cb86362b5896fdea5d to your computer and use it in GitHub Desktop.
Save Server4001/09cb86362b5896fdea5d to your computer and use it in GitHub Desktop.
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