Skip to content

Instantly share code, notes, and snippets.

@corpix
Created November 15, 2011 23:03
Show Gist options
  • Save corpix/1368660 to your computer and use it in GitHub Desktop.
Save corpix/1368660 to your computer and use it in GitHub Desktop.
jQuery - Easy ajax forms
var ajaxForms = function(/* TODO translations */){
var self = this;
$('form.ajax').each(function(i, form){
var f = $(form)
, submit = f.find('input[type="submit"]');
if($.fn.html5Uploader && f.hasClass('html5')){
f.find('[type="file"]').html5Uploader();
}
submit.click(function(){
var data = {}, errors = [];
f.find('[name]').each(function(i, input){
var field = $(input)
, v = self._validate(field);
for(var i in v) {
if(typeof v[i] == 'object')
errors.push(v[i]);
}
if(errors.length > 0)
return false;
var name = field.attr('name')
, val = field.val();
data[name] = val;
});
if(errors.length > 0) {
self._displayErrors(errors);
return false;
}
if(!data.csrf)
data.csrf = csrf;
$[f.attr('method')](f.attr('action'), data, function(res){
if(!res.error){
for(var i in data){
f.find('*[name="'+i+'"]').val('');
}
f.trigger('res', res);
}
}
);
return false;
})
});
}
ajaxForms.prototype._validate = function(field){
var classes = field.attr('class');
if(!classes)
return true;
classes = classes.split(/\s/g);
var result = [];
for(var i in classes){
if(this[classes[i]] instanceof Function)
result.push(this[classes[i]](field));
}
return result;
}
ajaxForms.prototype._displayErrors = function(errors){
for(var i in errors){
$.sticky(errors[i].error);
}
}
ajaxForms.prototype._getLabelOf = function(field){
var id = field.attr('id');
if(!id)
return '';
var label = field.closest('form.ajax').find('label[for="' + id + '"]');
if(!label)
return '';
return label.text();
}
ajaxForms.prototype.required = function(field){
if(!field.val()) {
var label = this._getLabelOf(field);
return { error: 'Поле "' + label + '" не заполнено' };
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment