Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(function ($) {
var defaults = {
cache: false,
contentType: false,
processData: false,
type: 'POST',
onProgress: new Function,
xhr: function (xhr) {
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', function(e) {
var percent = parseFloat(((e.loaded / e.total) * 100).toFixed(2));
defaults.onProgress(percent, e);
}, false);
return xhr;
},
};
$.fn.ajaxUpload = function (options) {
var formData = new FormData;
// if element is a form, find all inputs
if (this.is('form')) {
var $el = this.find(':input');
} else {
var $el = this;
}
$el.each(function() {
var $that = $(this);
var name = $that.attr('name');
var files = $that.prop('files');
var value = $that.val();
if (!name) return;
// when input not has file, we know that is a common input
if (!files) {
formData.append(name, value);
} else {
// Handles single file or multiple file
$.each(files, function(i, file) {
formData.append(name, file)
});
}
})
options = $.extend({}, defaults, options, {
data: formData
});
$.ajax(options);
}
})( jQuery );
@wallacemaxters
Copy link
Author

wallacemaxters commented Nov 24, 2015

O uso disso é

$('.change').change(function () {
     $('form.form-upload').ajaxUpload({url: 'testando'});
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment