1

The following form is what I use:

<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
    <input name="attachment" type="file" />
    <input type="submit" />
</form>

This is what I do with jQuery:

$('body').on('submit', '#form-attachment', function(e) {

    e.preventDefault();
    var data = $(this).serialize();

    console.log('fine', data);

    var url = 'imageupload.php';

    $.ajax({
        type : "POST",
        url : url,
        data : data,

        success : function(response) {
            console.log('success: ' + response);
        },
        complete : function(response) {
            console.log('complete: ', response);
        },
        error: function(response) { 
            console.log('error: ', response); 
        }
    });
});

And this is my imageupload.php file:

$response = array();
$response["c"] = isset($_FILES["attachment"]);

echo json_encode($response);

And this is result on console on submit():

success: {"c":false}

So, what is wrong? Why my file is not visible at all?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

2 Answers2

1

You can use FormData object, as shown below..

$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
 jQuery.ajax({
   type: "post",
   contentType: false,
   processData: false,
   url: jQuery(this).attr('action'),
   dataType: "json",
   data: data,
   success: function (r) {
    // Success Handeling
   }
  });
});

NOTE:- No need to append anything as other answer suggests. This method shall pass all the input fields just like they would in a normal http form POST method.

Community
  • 1
  • 1
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
0

Use FormData object.

Here's the example how to send file via jQuery ajax request:

$(document).on('change', 'input[type=file]', function() {
  formData = new FormData;
  formData.append('file', $(this)[0].files[0]);
  $.ajax {
    url: '/upload-url',
    data: formData,
    type: 'post',
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data);
    }
  }
});

In your case you should serialize form first, append serialized data to the formData object. Then get file (or files) from a file field and append it to the same formData object. And finally send the formData object via ajax.

Anton Grigoryev
  • 1,199
  • 11
  • 20