Skip to content

Instantly share code, notes, and snippets.

@tehbeard
Last active December 12, 2015 06:38
Show Gist options
  • Save tehbeard/4730546 to your computer and use it in GitHub Desktop.
Save tehbeard/4730546 to your computer and use it in GitHub Desktop.
$.fn.ajaxThatForm = function(opts){
this.each(function(i,el){
var formParams = {
action : $(this).attr("action"),
method : $(this).attr("method")
};
$.extend(formParams,opts);
var formData = new FormData();
$("input",el).each(function(i,formEl){
fel = $(formEl);
if(fel.is("[type=file]")){
if(fel[0].files.length == 0){
return;
}
if(fel[0].files.length == 1){
formData.append(
fel.attr('name'),
fel[0].files[0]);
}
else
{
for(x in fel[0].files){
formData.append(
fel.attr('name') + "-" + x,
fel[0].files[x]);
}
}
}
else
{
formData.append(fel.attr('name'),fel.val());
}
});
$.ajax({
url: formParams.action,
data: formData,
cache: false,
contentType: false,
processData: false,
async: true,
type: formParams.method,
success: function(data){
alert(data);
}});
});
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment