Submit form including uploading file via jQuery ajax

HTML:

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

How can I use $.ajaxto load an image and text value? I have no problem creating an object to send text data, but I have no idea where to start with the image.

I use a PHP server, so encoding an image in base64 or similar methods is perfectly acceptable.

+4
source share
2 answers

the easiest way is to use a class FormData():

So now you have a FormData object ready to be submitted with XMLHttpRequest. and add fields with a FormData object p>

<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 it will not contain the border line of the downloaded file.

+1

jQuery js ajax.

https://github.com/malsup/form/

var options = {
   url     : 'url',
   success : function(responseText) { "event after success "}
};

$(" form id ").ajaxSubmit(options);

php

0

All Articles