Search code examples
javascriptjqueryajaxform-data

How correctly pass data to php using ajax?


I am trying to send FormData to a PHP file. When pressing submit nothing happens, but when I send data separately it does work.

<form method="post" class="code_form" enctype="multipart/form-data">
  <input id="my_file_id2" class='upload_img' type="file" name="my_file">
  <input id="code" class='code' type="text" name="my_text">
  <input type="submit" id='fertig-btn' class='prime_sty' name="submit">
</form>
$(".code_form").on("submit", function(e) {
  var formData = new FormData();
  
  if ($(".upload_img").val() != '') {
    file = $(".upload_img").prop('files')[0];
    formData.append("my_file", file);
  }
  
  var dota = $(".code").val();
  
  $.ajax({
    type: "POST",
    url: "img_proc.php",
    cache: false,
    contentType: false,
    processData: false,
    data: {
      formData,
      dota,
    },
    success: function(data) {
      $(".user-success-code").html(data);
    }
  })

  e.preventDefault();
});

Sending data like this works:

data: formData,

Any idea how to solve it?


Solution

  • When sending data using a FormData object all information has to be in that object. Therefore you need to append() the value from .code to it, as you do with the file information. Try this:

    $(".code_form").on("submit", function(e) {
      var formData = new FormData();
      formData.append('dota', $(".code").val());
      
      if ($(".upload_img").val() != '') {
        formData.append("my_file", $(".upload_img").prop('files')[0]);
      }  
      
      $.ajax({
        type: "POST",
        url: "img_proc.php",
        cache: false,
        contentType: false,
        processData: false,
        data: formData,
        success: function(data) {
          $(".user-success-code").html(data);
        }
      })
    
      e.preventDefault();
    });