I want to make a convenience method for my Ajax calls as it is used extensively in the project.
As of now a typical call in the project looks like this.
$.post(
"url",
{
param1: value1,
param2: value2
},
function (data) {}
);
This call is repeated multiple times in the project with different parameters so I would like to be able to create a function to which I can pass the parameters and it will handle the entire Ajax call without me having to write the code every time. Expected Output:
var data= {firstName:"John", lastName:"Doe", age:46};
do_ajax_request(data);
The function do_ajax_request
in turn contains the actual Ajax code which makes the actual request and handles the result.
If possible I would also like for it to return a callback in case I need to perform any extra operations, would a promise work for that?
This would be a global function so I can access it from any JavaScript file.
I want to make a convenience method for my Ajax calls as it is used extensively in the project.
As of now a typical call in the project looks like this.
$.post(
"url",
{
param1: value1,
param2: value2
},
function (data) {}
);
This call is repeated multiple times in the project with different parameters so I would like to be able to create a function to which I can pass the parameters and it will handle the entire Ajax call without me having to write the code every time. Expected Output:
var data= {firstName:"John", lastName:"Doe", age:46};
do_ajax_request(data);
The function do_ajax_request
in turn contains the actual Ajax code which makes the actual request and handles the result.
If possible I would also like for it to return a callback in case I need to perform any extra operations, would a promise work for that?
This would be a global function so I can access it from any JavaScript file.
-
1
So just return the Ajax object
function do_ajax_request (data) { return $.post("url", data); }
and you can do what ever with the done, fail, always. – epascarello Commented Jan 10, 2018 at 15:37 -
So you want to write a wrapper for an
$.post
which is itself a wrapper for calls viaXMLHttpRequest
. Theres nothing inherently wrong with it (I have worked on at least one project which does exactly that), but be aware that its going to be hard to "makes the actual request and handles the result" for every possible case. – Jamiec Commented Jan 10, 2018 at 15:39 - @epascarello I never tried that, seems like it could work, will give it a try. – Jude Fernandes Commented Jan 10, 2018 at 15:44
-
1
@JudeFernandes Im really not sure how much of an increase in productivity you'd get. Where I have used it the "generic" stuff it does is to show/hide a loading overlay/message. But I essentially do exactly as epascarello says and return the
$.post
so I can deal with the result in situ. You cant possibly deal with every response in a generic way. – Jamiec Commented Jan 10, 2018 at 15:47 - 1 @Jamiec Lets say you have 20 calls to same endpoint. You either 1) hard code the stuff in multiple lines of exact call, 2) You use variables so you can at least make change in one place, 3) write a wrapper that simplifies it. If you do 1, copy and paste code is a BAD idea. Make a change, 20 places. #2 has same issue if you need to alter something not in a variable, and 3, you make change at one place. Basic idea of simplified code that is shared. There is nothing wrong with it. – epascarello Commented Jan 10, 2018 at 15:57
6 Answers
Reset to default 3So many plicated answers for something jQuery supports out of the box. Turning my ment to an answer.
You are basically just coding a wrapper for a wrapper so you do no have to recode some basic lines. No harm in that since it is easy to make the change in one place vs many.
So defined your function and just return the Ajax object that jQuery has. You can than use the done, fail, always methods.
function do_ajax_request (data) {
return $.post("url", data);
}
do_ajax_request({"foo":"bar"})
.done( function(){})
.fail(function(){})
do_ajax_request({"foo":"bar"})
.done( function(){})
.fail(function(){})
If you want to have mon code inside, you can do that too, basic idea for an error handler...
function do_ajax_request (data) {
var xhr = $.post("url", data);
xhr.fail(function () {
console.log(arguments)
});
return xhr;
}
I have written several jQuery plug-ins for use in my projects, and have brought along my ajax call method in nearly everyone. Here is a snippet of it from one of my projects. Enjoy!
Method Signature:
- obj = An object you want to pass to the ajax call in the data parameter. Pass null if not needed.
- method = ajax methods: POST, GET, PUT, DELETE, etc. Default is GET.
- endPoint = Url to call.
- returnType = html, json, text, etc.
- success = callback method when the call is successful.
- beforesend = method to call before the send. This is useful when you need to set headers before a call.
- failure = callback method when the call is unsuccessul.
var _api = { call: function (obj, method, endPoint, returnType, success, beforesend, failure) { obj = obj === null || undefined ? {} : obj; $.ajax({ method: method || 'GET', data: !$.isEmptyObject(obj) ? JSON.stringify(obj) : null, contentType: function () { switch (returnType) { case 'json': return 'application/json'; case 'text': return 'text/plain'; case 'buffer': return 'arraybuffer'; case 'html': default: return 'text/html'; } }(returnType === 'json' ? 'application/json; charset=utf-8' : ''), url: endPoint, dataType: returnType, beforeSend: function (xhr, obj) { if (beforesend) { beforesend(xhr, obj); } else { _api.showLoader(); } } }).done(function (data, textStatus, xhr) { if (success) success(data) }).fail(function (data, textStatus, xhr) { if (failure) failure() }).always(function () { // Implement code here that you want to run whenever the call is plete regardless of success or failure. }); } }
You could create a prototype to with a constructor to handle the input - make the request and handle the response:
ajax.requests = function ( data ) {
this.data = data;
return this.doRequest();
};
ajax.requests.prototype = {
doRequest : function () {
var _this = this;
$.ajax({
data: _this.data
}).done(function(data) {
Handle response and return!
});
}
};
// USAGE
var response = new ajax.requests( yourData );
By returning the $.post
, you can use a callback like .done()
, chain them together with .then()
, etc.
function do_ajax_request(data) {
return $.post( ... ); //RETURN the object
}
var myData = { ... };
do_ajax_request(myData).done(function(result) {
console.log("AJAX plete: " + result);
});
Just another take on this that maybe you hadn't considered. Rather than trying to wrap what is essentially already a wrapper, consider encapsulating your mon functionality, like handling errors and dealing with results and using this when executing an ajax request with the existing jQuery ajax wrapper(s)
function handleError(e){
// your mon error handling
}
function handleResult(result){
// your mon result handling
}
// then every time you execute a request, use your shared functionality
$.post(url, data)
.fail(handleError)
.done(handleResult);
Using code below, you'd need to import config object or declare on top of the functions.
I made two versions for POST and GET respectively
function getJSON(param, absoluteRestUrl = '') {
if (!absoluteRestUrl) {
absoluteRestUrl = config.adminRestEndpoint; // defaultUrl
}
return new Promise(async (resolve, reject) => {
let res = null;
res = await $.getJSON(absoluteRestUrl, param);
resolve(JSON.parse(JSON.stringify(res)));
});
}
function postJSON(param, absoluteRestUrl = '') {
if (!absoluteRestUrl) {
absoluteRestUrl = config.adminRestEndpoint; // defaultUrl
}
return new Promise(async (resolve, reject) => {
let res = null;
res = await $.post(absoluteRestUrl, param, null, 'json');
resolve(JSON.parse(JSON.stringify(res)));
});
}