Sureshkumar Menon
Sureshkumar Menon

Reputation: 1165

how to submit Form with AJAX Using enctype="multipart/form-data"?

how to submit Form with AJAX Using enctype="multipart/form-data"?

Upvotes: 10

Views: 27649

Answers (2)

Henning
Henning

Reputation: 16311

Short answer: you don't. You cannot upload files via AJAX.

The usual workaround is to set the target of your form to a hidden iframe and submit the form there, using a normal, non-AJAXy POST, to achieve the desired effect:

<form target="hiddenIframe" method="post" enctype="multipart/form-data">
    ...
</form>
<iframe name="hiddenIframe" id="hiddenIframe" style="display: none;" />

There's a jQuery plugin that uses this technique.

Edited to add:

XMLHttpRequest level 2 added support for uploading files via AJAX, and its browser support is now good and growing. Here's a browser support overview.

Upvotes: 12

George
George

Reputation: 6084

Here's a way that works even with IE8 and above:

Use malsup's jquery form plugin, which will take care of both XHR as well as the hidden iframe that IE needs for ajax upload.

Code snippet here:

<form id="formid" action="" enctype="multipart/form-data" method="POST" accept-charset="utf-8">
.
.
.
</form>

<script type="text/javascript">
        $(document).ready(function()
        {
            var options = { 
                cache:'false',   //IE FIX
                data: $('#formid').serialize(),
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(data) 
                {
                    //success action
                },
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                    //error action
                }
            }; 
            $('#formid').ajaxForm(options); 
        });
</script>

Upvotes: -1

Related Questions