-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.form-async.js
83 lines (79 loc) · 2.43 KB
/
jquery.form-async.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
$(function(){
"use strict";
/*
Usage Note:
-----------
*/
var _formatedErrors = function(errors) {
var out = {},error=null;
for (var field in errors) {
if (typeof errors[field] == 'object') {
for (var name in errors[field]) {
error = errors[field][name];
}
} else {
error = errors[field];
}
out[field] = error;
}
return out;
};
var _errors = function(form, errors) {
var errors = _formatedErrors(errors);
for (var field in errors) {
if (form.find('label[for="'+field+'"]').size()) {
form.find('label[for="'+field+'"]').
closest('.form-group').append('<p class="help-block">'+errors[field]+'</p>').addClass('has-error');
} else {
form.find('[name="'+field+'"]').
closest('.form-group').append('<p class="help-block">'+errors[field]+'</p>').addClass('has-error');
}
}
};
$(document).on('submit', 'form[data-async]', function(event) {
event.preventDefault();
var form = $(this),
target=null;
if (form.closest('.tab-pane').size()) {
target = form.closest('.tab-pane');
} else if (form.closest('.modal-content').size()) {
target = form.closest('.modal-content');
} else {
target = form.parent();
}
form.ajaxSubmit({
dataType: 'json',
beforeSubmit: function(arr, form) {
target.find('button,input[type=submit]').attr('disabled','disabled');
form.find('.has-error .help-block').remove();
form.find('.form-group').removeClass('has-error');
},
success: function(json, statusText, xhr, form) {
target.find('.indicator').remove();
target.find('button,input[type=submit]').removeAttr('disabled');
form.find('button,input[type=submit]').removeAttr('disabled');
if (json.redirect_to) {
location.href = json.redirect_to;
} else if (json.cb) {
$(window).trigger(json.cb,[form,json.args]);
} else {
location.reload();
}
},
error: function(xhr, status, error, form){
var json = xhr.responseJSON;
target.find('.indicator').remove();
target.find('button,input[type=submit]').removeAttr('disabled');
form.find('button,input[type=submit]').removeAttr('disabled');
if (_(json.errors).size()) {
_errors(form, json.errors);
} else {
$.bootstrapGrowl((json.name?json.name:json.message), {
type: 'danger',
offset: {from: 'bottom', amount: 20}
});
}
}
});
});
});