How to use FormData for AJAX file upload?
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object herevar formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();formData.append('section', 'general');formData.append('action', 'previewImg');// Attach fileformData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({ url: 'Your url here', data: formData, type: 'POST', contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+) processData: false, // NEEDED, DON'T OMIT THIS // ... Other options like success and etc});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST"
in options since all files must be sent via POST request.
Note: contentType: false
only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({ url: 'Your url here', data: formData, type: "POST", //ADDED THIS LINE // THIS MUST BE DONE FOR FILE UPLOADING contentType: false, processData: false, // ... Other options like success and etc})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);formData.append('tax_file', $('input[type=file]')[0].files[0]);$.ajax({ type: "POST", url: base_url + "member/upload/", data: formData, //use contentType, processData for sure. contentType: false, processData: false, beforeSend: function() { $('.modal .ajax_data').prepend('<img src="' + base_url + '"asset/images/ajax-loader.gif" />'); //$(".modal .ajax_data").html("<pre>Hold on...</pre>"); $(".modal").modal("show"); }, success: function(msg) { $(".modal .ajax_data").html("<pre>" + msg + "</pre>"); $('#close').hide(); }, error: function() { $(".modal .ajax_data").html( "<pre>Sorry! Couldn't process your request.</pre>" ); // $('#done').hide(); }});
you can use.
var form = $('form')[0]; var formData = new FormData(form); formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.