Send data and files through multi-part forms with FormData in HTML using ajax

DINOLIN Y P JOB :

In the below code, I'm able to transfer data but when I use the function append to transfer file and data it's not working. Can someone tell me how to transfer file from upload? Looking forward to some help

$(document).ready(function() {
  var loader = '<img src="../assets/media/loader.gif" />';

  $('#submit').click(function() {
    confirm("Do you really want to send messages?");
    $('.loading').html(loader).fadeIn();

    var msg_area_cst = $('textarea[name=msg_area_cst]').val();
    var num_cst = $('textarea[name=num_cst]').val();

    var form_data = new FormData();
    form_data = 'msg_area_cst=' + msg_area_cst + '&num_cst=' + num_cst;
    form_data.append('upload', $('input[name=upload]'));

    $.ajax({
      url: "../server/CustomMsg.php",
      type: "POST",
      data: form_data,
      success: function(html) {
        if (html == 1) {
          $('#register_form').fadeOut('slow');
          $('.loading').fadeOut();
          $('.message').html('Successfully Sent ! ').fadeIn('slow');
        } else 
          alert('Sorry, unexpected error. Please try again later.');
      }
    });
  });
});
Rory McCrossan :

The problem is because you correctly declare a FormData object, but then in the next line overwrite it immediately with a string.

You need to append() all data to the FormData object. In addition you need to provide the file data to the append() method, not the jQuery object referencing the input type="file" control.

var form_data = new FormData();
form_data.append('msg_area_cst', msg_area_cst);
form_data.append('num_cst', num_cst);
form_data.append('upload', $('input[name=upload]')[0].files[0]);

That being said, you can make this much more simple if the controls you're reading the values from are contained in a form element. Then you can use the submit event of that form and pass a reference to it to the FormData constructor.

Also you don't do anything with the result of the confirm() I assume you want to stop the form submission if Cancel is clicked, which the above example now does using preventDefault().

Finally, using html == 1 is very unreliable. Firstly html will be a string so relying on implicit type coercion to an integer is not ideal. Also, returning a plain text response can cause issues if there's any whitespace included. I'd strongly suggest you change your server side logic to return a serialised format, such as JSON, and use a boolean value for a 'success' flag.

With all that said, try this:

$('#yourForm').on('submit', function(e) {
  if (!confirm("Do you really want to send messages?")) {
    e.preventDefault();
  }
  
  $('.loading').html(loader).fadeIn();

  $.ajax({
    url: "../server/CustomMsg.php",
    type: "POST",
    data: new FormData(this),
    success: function(html) {
      if (html.trim() === "1") {
        $('#register_form').fadeOut('slow');
        $('.loading').fadeOut();
        $('.message').html('Successfully Sent ! ').fadeIn('slow');
      } else
        alert('Sorry, unexpected error. Please try again later.');
      }
    }
  });
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=30057&siteId=1