Last active
August 29, 2015 14:24
-
-
Save Server4001/09cb86362b5896fdea5d to your computer and use it in GitHub Desktop.
jQuery deferred object example using AJAX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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