Request not going with `$.ajax` call in jQuery

401 Views Asked by At

I need to make an ajax call with jQuery and need to pass diffrent ajax options base on the result of a if/else condition.

This is how I tried it:

var url = 'form_submission.php';
if (imgAttached) {
  var params     = $form.serializeArray(),
      formData   = new FormData(),
      files      = $form.find('[name="images"]')[0].files;

  $.each(files, function(i, file) {
    formData.append('images-' + i, file);
  });
  
  $.each(params, function(i, val) {
    formData.append(val.name, val.value);
  });

  var ajaxOptions  =  " url:"+url
      ajaxOptions +=  ",type:"+'post'
      ajaxOptions +=  ",data:"+formData
      ajaxOptions +=  ",cache:"+false
      ajaxOptions +=  ",contentType:"+false
      ajaxOptions +=  ",processData:"+false; 

} else {
  var formData = $form.serialize();

  var ajaxOptions  =  " url:"+url
      ajaxOptions +=  ",type:"+'post'
      ajaxOptions +=  ",data:"+formData;
} 

This is how I call ajax request from outside if/else:

$.ajax({        
  ajaxOptions,        
  beforeSend: function() {},
  success: function(json) {}
)}

My problem is request is not going with ajaxOptions and when I trying with standard way its working. Can anybody tell what would be the issue here?

1

There are 1 best solutions below

0
zx01 On BEST ANSWER

$.ajax() function takes an object as a parameter i.e. it should have key-value pairs.

Here, in $.ajax({ ajaxOptions, .....}), ajaxOptions is a string formed by concatenation, instead of being key-value pairs.

Expected

url: 'form_submission.php',
method: 'POST'

Actual

"url: 'form_submission.php', method: 'POST'"

To fix this, create an ajaxOptions object and pass it to the $.ajax() function by extracting the properties using spread operator.

if (imgAttached) {
  .
  .
  .
  const ajaxOptions = {
    url: url,
    type: "POST",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
  };
} else {
  .
  .
  .
  const ajaxOptions = {
    url: url,
    type: "POST",
    data: formData,
  };
}

$.ajax({        
  ...ajaxOptions,        
  beforeSend: function() {},
  success: function(json) {}
)}