Reputation: 5799
I am creating a application where I have lot of ajax calls to a remote server and use them extensively. As the code is almost same in all calls, I want to create a new function which I can reuse. I am struck up in defining the parameter structure for the "data" parameter. I will explain below my problem.
Sample of my current ajax call is provided below.
Current Call Sample:
$.ajax({
beforeSend: function() {
$.mobile.loading('show');
},
complete: function() {
$.mobile.loading('hide');
},
type: 'GET',
url: 'http://localhost/test-url/',
crossDomain: true,
data: {appkey: '1234567', action: 'action1','name':'me'},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: false,
error: function() {
//some operations
},
success: function(data) {
//some operations
}
});
The re-usable function that I have created:
function newAjax(parm, successCallback, errorCallback) {
$.ajax({
beforeSend: function() {
$.mobile.loading('show');
},
complete: function() {
$.mobile.loading('hide');
},
type: 'GET',
url: 'http://localhost/test-url',
crossDomain: true,
data: {appkey: '1234567', parm: parm},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: false,
success: function() {
successCallback();
},
error: function() {
errorCallback();
}
});
}
Question:
I will be passing the the parameters for the ajax call via "parm" parameter. I want the data value to be directly added to the parent "data" parameter. And not as a sub-object of data. The appKey remains same across all calls and so I keep it in the actual function.
I want both the success and error callback functions to be optional. If not provided they should be ignored.
Upvotes: 2
Views: 4686
Reputation: 75307
You can use the jQuery.extend
method to combine two or more objects together.
data: jQuery.extend({appkey: '1234567'}, parm),
You can check that you were actually passed functions for successCallback
and errorCallback
using typeof var === 'function'
;
success: function () {
if (typeof successCallback === 'function') {
successCallback();
}
},
error: function () {
if (typeof errorCallback === 'function') {
errorCallback();
}
}
... although it might be nicer if you just returned the Promise created by the AJAX request, and let the caller add their success, error handlers if they wanted;
function newAjax(parm) {
return jQuery.ajax({
/* as before, but without success and error defined */
});
}
... then:
newAjax().done(function () {
// Handle done case
}).fail(function () {
// Handle error case.
});
If a caller doesn't want to add an error handler, they just don't call fail()
;
newAjax().done(function () {
// Handle done case
});
Upvotes: 5