Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form including file upload via jQuery ajax

Tags:

html

jquery

php

HTML:

<input type="text" name="description">
<input type="file" name="image" accept=".jpg">

How can I use $.ajax to upload the image and text value? I have no problem producing an object to submit text data, but have no idea where to start with the image.

I am using PHP server-side, so encoding the image in base64 or similar methods are perfectly acceptable.

like image 222
GiantDuck Avatar asked Nov 10 '22 12:11

GiantDuck


1 Answers

it’s easiest to use the FormData() class:

So now you have a FormData object, ready to be sent along with the XMLHttpRequest. and append fields with FormData Object

<script type="text/javascript">
           $(document).ready(function () {
               var form = $('form'); //valid form selector
               form.on('submit', function (c) {
                   c.preventDefault();

                   var data = new FormData();
                   $.each($(':input', form ), function(i, fileds){
                       data.append($(fileds).attr('name'), $(fileds).val());
                   });
                   $.each($('input[type=file]',form )[0].files, function (i, file) {
                       data.append(file.name, file);
                   });
                   $.ajax({
                       url: '/post_url_here',
                       data: data,
                       cache: false,
                       contentType: false,
                       processData: false,
                       type: 'POST',
                       success: function (c) {
                            //code here if you want to show any success message
                       }
                   });
                   return false;
               });
           })
</script>

and forcing jQuery not to add a Content-Type header for you, otherwise, the upload file boundary string will be missing from it.

like image 72
Girish Avatar answered Nov 14 '22 23:11

Girish