how to do file upload using jquery serialization

241,502

Solution 1

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, ...

Solution 2

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)
        {
            

        }
    });        

});

Solution 3

   var form = $('#job-request-form')[0];
        var formData = new FormData(form);
        event.preventDefault();
        $.ajax({
            url: "/send_resume/", // the endpoint
            type: "POST", // http method
            processData: false,
            contentType: false,
            data: formData,

It worked for me! just set processData and contentType False.

Solution 4

HTML

<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
    <input id="name" name="name" placeholder="Enter Name" type="text" value="">
    <textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
    <select name="gender" id="gender">
        <option value="male" selected="selected">Male</option>
        <option value="female">Female</option>
    </select>
    <input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>

JavaScript

var data = new FormData();

//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
    data.append(input.name, input.value);
});

//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
    data.append("my_images[]", file_data[i]);
}

//Custom data
data.append('key', 'value');

$.ajax({
    url: "URL",
    method: "post",
    processData: false,
    contentType: false,
    data: data,
    success: function (data) {
        //success
    },
    error: function (e) {
        //error
    }
});

PHP

<?php
    echo '<pre>';
    print_r($_POST);
    print_r($_FILES);
    echo '</pre>';
    die();
?>

Solution 5

You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.

$.ajax({
    url: "ajax.php", 
    type: "POST",             
    data: new FormData('form'),
    contentType: false,       
    cache: false,             
    processData:false, 
    success: function(data) {
        $("#response").html(data);
    }
});
Share:
241,502

Related videos on Youtube

kamikaze_pilot
Author by

kamikaze_pilot

Updated on July 08, 2022

Comments

  • kamikaze_pilot
    kamikaze_pilot almost 2 years

    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

  • Rook777
    Rook777 about 11 years
    This is no longer true. With a <input type='file' name='myfile'/> and the FormData() object, one can save a file using AJAX very simply. See Silver89's answer below.
  • Darin Dimitrov
    Darin Dimitrov about 11 years
    @Rook777, that's of course true if the browser you are using supports the HTML5 File API. Have you tried this in IE how simple it is? Until HTML5 becomes a standard and supported by all browsers there will be plugins because you cannot upload files using AJAX.
  • Rook777
    Rook777 about 11 years
    You are correct. I am lucky enough to be in a development environment that does not support IE so I forgot to consider it. Yes, without HTML5 compatibility, this feature will not work. According to caniuse.com/xhr2, only IE 10+ supports this feature so far.
  • user1570144
    user1570144 over 9 years
    jQuery Form Plugin is great!
  • Mohamed Ali
    Mohamed Ali over 8 years
    what is 'form' in new FormData('form') ,is it the id, it doesn't work for me
  • Rossco
    Rossco over 8 years
    Yes this would typically be the form id
  • Mohamed Ali
    Mohamed Ali over 8 years
    to me it works only with document.forms.form instead of 'form' string, passed to the FormData constructor
  • Muhammad Tarique
    Muhammad Tarique over 4 years
    How to send submit button name?
  • Renish Patel
    Renish Patel over 4 years
    @MuhammadTarique You just add button like <button type="button" name="button_name" value="Contact Button">Submit</button> and you get response button_name = "Contact Button" at php side
  • Muhammad Tarique
    Muhammad Tarique over 4 years
    Thanks for your reply but I don't think it will work this way. However I've already done this by using formData.append("btnName", "true");
  • Renish Patel
    Renish Patel over 4 years
    @MuhammadTarique This example already added in this post like data.append('key', 'value');
  • Jeppe Mariager-Lam
    Jeppe Mariager-Lam over 3 years
    Important note on this: processData: false, contentType: false, is needed to avoid an Illegal invocation error, as without these, jQuery will try to convert the formdata to a string when sending it, which is not wanted in this case.
  • Eatsam ul haq
    Eatsam ul haq almost 2 years
    But this is when you only want to upload a file. What if our form has input fields as well. Is there a way to use FormData() when we have a file and input fields in our form? doing processData: false, contentType: false will not convert input fields data into String.