Reputation: 10228
Here is a part of my code:
if ( external_link ) {
data = {external_link : external_link};
} else {
data = form_data;
}
$.ajax({
url: base_url + frm.attr('action'),
type: frm.attr('method'),
data: data,
cache: false,
contentType: false, // this
processData: false, // and this should be removed when external_link isn't false
success: function (imageUpload) {
All I'm trying to do is making contentType: false
and processData: false
parameters dynamic. I mean, if the condition above was true, then those two mentioned parameters should be removed. How can I do that?
Upvotes: 1
Views: 701
Reputation: 3207
Pass an object into ajax call instead creating a literal object there? Preferably by wrapping a function around the call.
Code below is not direct implementation but showcase of principle:
var makeAjaxAndExecute = function(param1, param2){
var ajaxObjectInitiate = {object literal here}
ajaxObjectInitiate.param1 = param1;
ajaxObjectInitiate.param2 = param2;
$.ajax(ajaxObjectInitiate //.... rest of your code
}
You can further separate configuring the object and actually making the call, you can have general generator of requests elsewhere totally depends what are your needs and how complex do you wanna / need it to be.
If you need to do it on a lot of calls, I would opt for totally isolated builder that holds onto object and has getters and setters for options and possibly internal states and logic. And once object is set simple pass it to ajax call.
Scale-able, maintainable and easy to debug but not needed if you have simple logic as this.
Upvotes: 0
Reputation: 5589
What about defining the minimum set of options first, and add the other two if the condition is met?
var options = {
url: base_url + frm.attr('action'),
type: frm.attr('method'),
data: data,
cache: false,
success: function (imageUpload) {
...
};
if ( external_link ) { // the external link entered
options.contentType: false; // this
options.processData: false; // and this should be removed when external_link isn't false
options.data = {external_link : external_link};
} else {
options.data = form_data;
}
$.ajax(options);
Upvotes: 0
Reputation: 8078
var ajaxParams = {
url: base_url + frm.attr('action'),
data: data
// contentType not here
};
if (something) {
ajaxParams.contentType = false; // add new parameter
}
$.ajax(ajaxParams);
Upvotes: 7