Last active
November 7, 2017 20:11
-
-
Save wuori/2c780e734235a6d1625235ce18f3f0e8 to your computer and use it in GitHub Desktop.
FormData() Handling Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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