Reputation: 8156
I would like to skip all this piece of code if some preconditions are not met, but I also want to move all the code between the parenthesis in a function. Is it allowed? I don't understand how this syntax works.
$.ajax({
type: "POST",
url: urlAppend,
data: JSON.stringify(xxx),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: function (result) {
if (canceled) {
return;
}
//Long code
}
//Long code 2
},
error: function (request, error) {
alert('ppp');
}
});
Upvotes: 0
Views: 8229
Reputation: 12132
Try this:
function runAjax(params){
$.ajax({
type: params["post"],
url: params["url"],
data: params["data"],
contentType: params["content_type"],
dataType: params["json"],
processdata: params["process_bool"],
success: function (result) {
if (params["canceled"]) {
return;
}
//Long code
}
//Long code 2
},
error: function (request, error) {
alert('ppp');
}
});
}
if(condition){
var options = {
//set options here
};
runAjax(options);
}
Upvotes: 1
Reputation: 3200
Take a look at this sample:
function callAjax(condition) {
if (condition) {
$.ajax({
type: "POST",
url: urlAppend,
data: JSON.stringify(xxx),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: function (result) {
if (canceled) {
return;
}
//Long code
}
//Long code 2
},
error: function (request, error) {
alert('ppp');
}
});
}
}
// Somewhere in your code
callAjax(condition);
Upvotes: 1
Reputation: 6888
function doComplexStuff(){
}
$.ajax({
type: "POST",
url: urlAppend,
data: JSON.stringify(xxx),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: false,
success: doComplexStuff,
error: function (request, error) {
alert('ppp');
}
});
The doComplexStuff
will automatically receive all the params that the success function receives.
Upvotes: 1
Reputation: 47986
Place your $.ajax
call into a function, then wrap the call to the function in a conditional expression:
function makeRequest(){
$.ajax( ... )
}
if ( some_condition ){
makeRequest();
}
Keep in mind that you are using some variables inside the AJAX callback (namely the canceled
variable). You'll have to make that variable available to the function.
Upvotes: 5