Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do file upload using jquery serialization

So I have a form and I'm submitting the form through ajax using jquery serialization function

        serialized = $(Forms).serialize();          $.ajax({          type        : "POST",         cache   : false,         url     : "blah",         data        : serialized,         success: function(data) {          } 

but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything

like image 464
kamikaze_pilot Avatar asked Dec 28 '10 09:12

kamikaze_pilot


2 Answers

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event) {     event.preventDefault();     $.ajax({         url: $(this).attr("action"),         type: $(this).attr("method"),         dataType: "JSON",         data: new FormData(this),         processData: false,         contentType: false,         success: function (data, status)         {          },         error: function (xhr, desc, err)         {                       }     });          }); 
like image 134
Shaiful Islam Avatar answered Sep 18 '22 08:09

Shaiful Islam


A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:

$(function() {     $('#ifoftheform').ajaxForm(function(result) {         alert('the form was successfully processed');     }); }); 

The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...

like image 29
Darin Dimitrov Avatar answered Sep 18 '22 08:09

Darin Dimitrov