jquery post file upload code example
Example 1: Upload image via ajax (jquery)
var form = new FormData();
form.append('varName','data');
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
},
error: function(data){
}
});
Example 2: file upload in jquery
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
Example 3: How can I upload files asynchronously
$(':button').on('click', function () {
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData($('form')[0]),
cache: false,
contentType: false,
processData: false,
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
}
});
});