Last active
August 29, 2015 13:56
-
-
Save sabind/8968858 to your computer and use it in GitHub Desktop.
Wrapping an Ajax call with a callback.
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
| 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); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)