Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active June 24, 2016 12:10
Show Gist options
  • Save wallacemaxters/7f29b8c8702d06a2afdf to your computer and use it in GitHub Desktop.
Save wallacemaxters/7f29b8c8702d06a2afdf to your computer and use it in GitHub Desktop.
(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

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