$.ajax if condition
I failed to write a condition inside of ajax by using the following syntax.
var num = 1;
$.ajax({
type: "POST",
//condition starts
if (num === 1){
url: url1,
data: data1,
}else{
url: url2,
data: data2,
}
//condition finishes
success: success,
dataType: dataType
});
but this way works.
var num = 1;
if(num === 1){
$.ajax({
type: "POST",
url: url1,
data: data1,
success: success,
dataType: dataType
});
}else{
$.ajax({
type: "POST",
url: url2,
data: data2,
success: success,
dataType: dataType
});
}
the 2nd method is not quite ideal as repeating my code.
is my first script in a wrong syntax? Could someone please point out? thanks
is my first script in a wrong syntax?
Yes, absolutely. You were just inserting if-else-statement parts in the middle of an object literal. You should use something like this:
var params = {
type: "POST",
success: success,
dataType: dataType
};
if (num == 1) {
params.url = url1;
params.data = data1;
} else {
params.url = url2;
params.data = data2;
}
$.ajax(params);
Or if you want to inline them, you can use the ternary operator:
$.ajax({
type: "POST",
url: (num == 1) ? url1 : url2,
data: (num == 1) ? data1 : data2,
success: success,
dataType: dataType
});
(If you don’t want to repeat the condition, store its boolean result in a variable)
You could do it like this:
var num = 1, url, data;
if (num === 1) {
url = url1;
data = data1;
} else {
url = url2;
data = data2;
}
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
The stuff in the {
braces }
is an object literal. You can declare it and modify it before you call $.ajax
.
var options =
{
type: "POST",
url: url2,
data: data2,
success: success,
dataType: dataType
};
if (num === 1) { options.url = url; options.data = data; }
$.ajax(options);
$.ajax
takes a regular JavaScript object, so you can fill it in piecewise:
request = {type: "POST", success: success, dataType: dataType};
if(num == 1) {
request.url = url1;
request.data = data1;
} else {
request.url = url2;
request.data = data2;
}
$.ajax(request);
Try this way if url and data are very simple.
var num = 1;
$.ajax({
type: "POST",
url : (num==1? url1 : url2),
data: (num==1? data1 : data2),
success: success,
dataType: dataType
});
Place the condition before the ajax statements and assign common variables there.
Try this:
var num = 1;
$.ajax({
type: "POST",
url: (num === 1 ? url1 : url2)
data: (num === 1 ? data1 : data2)
success: success,
dataType: dataType
});
But as others have mentioned it would be best to just assign variables outside of the ajax call.