Reputation: 2097
I'm fairly new to jQuery and Javascript so this may be simple.
I have a function that calls a service using $.ajax()
. The service calls work correctly but now it's time to go back and cleanup a few things. For example, whenever I call the service, I create a new function and copy / paste a bunch of code. Bad practice, I know, but I was prototyping.
I'd like to have a single function that calls the service and pass that function the names of the callback functions. In the code below, I want to pass the names of the functions to be called on success, error, and complete. I also want to the arguments to be passed to the functions. For example, I want the function GetCurrentPricing
to be called on success and I want the response to be passed to the GetCurrentPricing
function.
How do I do this?
function CallTheService() {
$.ajax(
{
url : varUrl,
type : varType,
cache : varCacheBool,
data : varData,
contentType : varContentType,
processdata : varProcessData,
dataType : varDataType,
async : varAsync,
success : function(response) {},
error : function(err) {},
complete : function() {}
}
)
}
Upvotes: 1
Views: 72
Reputation: 67296
Something like this should work:
var successFunction = function(response) { GetCurrentPricing(); };
function CallTheService(successFunction) {
$.ajax(
{
url : varUrl,
type : varType,
cache : varCacheBool,
data : varData,
contentType : varContentType,
processdata : varProcessData,
dataType : varDataType,
async : varAsync,
success : successFunction,
error : function(err) {},
complete : function() {}
}
)
}
Upvotes: 0
Reputation: 48899
I would do something like:
var success = function(response) { alert(response); };
function CallTheService(success) {
$.ajax(
{
url : varUrl,
type : varType,
cache : varCacheBool,
data : varData,
contentType : varContentType,
processdata : varProcessData,
dataType : varDataType,
async : varAsync,
success : function(response) { success.call(response); },
error : function(err) {},
complete : function() {}
}
)
}
Upvotes: 0
Reputation: 17451
Do something like:
success: function(response) {GetCurrentPricing(whateverparameters)},
Upvotes: 0
Reputation: 6394
You can simply call the function at:
success: function(response){
GetCurrentPricing(response)
},
Thats what those options are for :)
Upvotes: 1