Skip to content

Instantly share code, notes, and snippets.

@sabind
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save sabind/8968858 to your computer and use it in GitHub Desktop.

Select an option

Save sabind/8968858 to your computer and use it in GitHub Desktop.
Wrapping an Ajax call with a callback.
var sendAjaxRequest = function(path, data, callback) {
$.ajax({
url: path,
type: "POST",
data: data,
headers: {accept: 'application/json'}, //optional based what kind of stuff you need
success: function (response) {
// Response is what you get back. it's contents are based on the API you're calling
if (response.success) {
callback(response.success, response.data, response.code);
}
else {
callback(false, response.data, response.code);
}
},
error: function (jqXHR, textStatus, errorThrown) {
callback(jqXHR && jqXHR.readyState == 4 && jqXHR.responseText ? jqXHR.responseText : errorThrown);
}
});
};
//Note this functions only GETs
var sendAjaxGetRequest = function(path, callback){
$.ajax({
url: path,
headers: {accept: 'application/json'}, //optional based what kind of stuff you need
success: function (response) {
// Response is what you get back. it's contents are based on the API you're calling
if (response.success) {
callback(response.success, response.data, response.code);
}
else {
callback(false, response.data, response.code);
}
},
error: function (jqXHR, textStatus, errorThrown) {
callback(jqXHR && jqXHR.readyState == 4 && jqXHR.responseText ? jqXHR.responseText : errorThrown);
}
});
};
var callbackFunction = function (status_result, result, result_code) {
if (status_result) {
//Do some success code
console.log(result);
} else {
//Do some fail code
alert('FAILED!')
console.log(result);
}
};
//Use the whole system like this
//No the callback function is used without paranthesis so that it's base as a whole.
//The ajax function will invoke it with paranthesis
sendAjaxRequest('/some/url/thing', {field: 'Field'}, callbackFunction);
@sabind
Copy link
Author

sabind commented Feb 21, 2014

This code does require jQuery. If you're building desktop applications I don't find any problems including it. Sometimes if you're on mobile it may not be a good idea to force your users to download the lib (there are smaller counterparts)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment