Reputation: 2386
I have the following code multiple times:
$.ajax({
type: "POST",
cache: false,
url: "url here",
success: function (data) {
// do something here...
}
});
I'd like to turn this into a function as use it only once, somthing like:
function ajax (type, url, complete){
$.ajax({
type: type,
cache: false,
url: url,
success: function (data) {
GO TO THE METHOD SPECIFIED IN complete
}
});
How would I run a method specified in the complete variable? Is it possible? I've looked at the ajax success event for jQuery but since it would be triggered on every item that uses it, I would then have to check if it is the correct ajax request...
Upvotes: 0
Views: 1877
Reputation: 171679
If understand question correctly
function ajax (type, data, url, complete){
$.ajax({
type: type,
data:data,
cache: false,
url: url,
success: complete
});
}
var obj={ id:1}
/* example case use */
ajax ('POST', obj 'site.com', myAjaxComplete);
/* a success callback from ajax*/
function myAjaxComplete(data){
// data argument is return data from server
}
EDIT: you'll definitely want to add an argument for data to send to server
Upvotes: 0
Reputation: 11524
If complete
is a reference to a function,
function ajax (type, url, complete){
$.ajax({
type: type,
cache: false,
url: url,
success: complete
});
Just make sure complete
's arguments match what is given by success
.
EDIT: If complete
is an object, just find the function on it and use that:
success: complete.foo
Hope this is what you're asking...
Upvotes: 2