Skip to content

Instantly share code, notes, and snippets.

@wuori
Last active November 7, 2017 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuori/2c780e734235a6d1625235ce18f3f0e8 to your computer and use it in GitHub Desktop.
Save wuori/2c780e734235a6d1625235ce18f3f0e8 to your computer and use it in GitHub Desktop.
FormData() Handling Example
/*
* Create new FormData() object from values in $form
*/
getFormData: function($form) {
var data = new FormData();
var specialTypes = ['file', 'checkbox', 'radio'];
$form.find('input,textarea,select').each(function() {
var type = $(this).attr('type');
if (specialTypes.indexOf(type) === -1) {
data.append($(this).attr('name'), $(this).val());
} else if (type == 'file') {
data.append($(this).attr('name'), $(this)[0].files[0]);
} else if (type == 'radio' && $(this).is(':checked')) {
data.append($(this).attr('name'), $(this).val());
} else if (type == 'checkbox') {
if ($(this).is(':checked')) {
data.append($(this).attr('name'), $(this).val());
} else {
data.append($(this).attr('name'), '');
};
};
});
return data;
},
var data = Ritual.forms.getFormData($form);
var jqxhr = $.ajax({
type: 'POST',
processData: false,
contentType: false,
url: $form.attr('action'),
data: data
})
.done(function(res) {
// handle errors if any
if (Ritual.forms.handleFormErrors($form, res)) {
if (opts.successHandler !== 'undefined') {
opts.successHandler.call(opts.ns, $el, $modal, res);
}
_self.resetForm($modal);
} else {
// has errors
return false;
}
})
.fail(function(res) {
Ritual.forms.handleFormFail($form, res)
})
.always(function() {
// reset modal
_self.handleAlways($modal)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment