Skip to content

Instantly share code, notes, and snippets.

@probil
Last active May 14, 2018 21:52
Show Gist options
  • Save probil/0ac5160febbdfc429e5e to your computer and use it in GitHub Desktop.
Save probil/0ac5160febbdfc429e5e to your computer and use it in GitHub Desktop.
Usefull function to serialize form inputs including input[type=file]
//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
var obj = $(this);
/* ADD FILE TO PARAM AJAX */
var formData = new FormData();
$.each($(obj).find("input[type='file']"), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
formData.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
return formData;
};
})(jQuery);
$('form.edit-account-form').submit(function(e){
//stop std action
e.stopPropagation();
e.preventDefault();
//send data
$.ajax({
type : 'POST',
url : $(this).attr('action'),
data : $(this).serializefiles(),
processData: false,
contentType: false,
success : function(data){
console.log(data);
}
});
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment