2

I'm trying to create an ajax upload form that sends both a file and a text input. I've managed to send the file with the following code:

var $form = $('#form');
var formData = new FormData();

formData.append('file', $('#file')[0].files[0]);

$.ajax({
    url: 'upload.php',
    type: 'POST',
    dataType: 'html',
    data: formData,
    processData: false,
    contentType: false
});

However, I also need to send the text input, so I've tried passing the whole form to the FormData object:

var $form = $('#form');
var formData = new FormData($form);

$.ajax({
    url: 'upload.php',
    type: 'POST',
    dataType: 'html',
    data: formData,
    processData: false,
    contentType: false
});

But then I get nothing in 'upload.php'

How can I send the text and the file inputs together?

Thanks!

tamir
  • 3,207
  • 2
  • 33
  • 51

1 Answers1

0

Found this answer (Previous Answer) after much searching and works great in my application:

$("form#data").submit(function(){

var fd = new fd($(this)[0]);

var request = jQuery.ajax({
  url: gurl,
  type: 'POST',
  cache: false,
  contentType: false,
  processData: false,
  data: fd
  });

I would also check your AJAX call, the dataType: 'html' might cause errors.

Community
  • 1
  • 1
J W
  • 2,801
  • 2
  • 18
  • 22
  • Be Cautious that in non HTML 5 browsers i.e. versions of IE < 10 this solution will not work, as FormData is an HTML5 object, not present in IE 8 or 9. – user1697113 Mar 21 '16 at 01:46