-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.ajaxform.js
More file actions
executable file
·380 lines (321 loc) · 11.6 KB
/
jquery.ajaxform.js
File metadata and controls
executable file
·380 lines (321 loc) · 11.6 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
log = function(value) {
if (console && console.log) {
console.log(value);
}
};
(function($) {
/****************** Helper functions ********************/
/**
* @params $container jQuery object of possible container (div, span, etc)
* @params errors array of error for the container
*/
var renderError = function(params) {
var $container = params.container;
var errors = params.errors;
var errorElement = $container.find('> .error');
if (errorElement.length == 0) {
errorElement = $('<div class="error" />');
$container.append(errorElement);
}
if (errors != null) {
$container.addClass(settings.class_bad).removeClass(settings.class_good);
errorElement.css('display', 'block').html(errors.join('<br/>'));
}
else {
$container.addClass(settings.class_good).removeClass(settings.class_bad);
errorElement.css('display', 'none').html('');
}
};
var onSessionStart = function($form) {
$form.find('input:text, input:password, textarea').hint('removeHint');
};
var onSessionEnd = function($form) {
$form.find('input:text, input:password, textarea').hint('showHint');
};
/**
* Serialize form data + any custom data
*
* @param data
* @returns
*/
var serialize = function(form, data) {
try
{
var serializedData = form.serializeArray();
}
catch (e)
{
// TODO: handle exception
log(e);
}
for ( var key in data) {
value = $.toJSON(data[key]);
serializedData.push({
name : key,
value : value
});
}
return $.param(serializedData, false);
};
/****************** Class starts here functions ********************/
/**
* @param $form jQuery Form element
* @options options {} - see AjaxForm.options and jQuery.ajax for supported options
*/
var AjaxForm = function($form, options) {
this.$form = $form;
var ajaxForm = this;
if (!options) {
options = {};
}
// Guess which buttons we should disable when submit is triggered
if (!options.buttons) {
options.buttons = $form.find(':button, :submit');
}
// Try to guess url to submit to
if (!options.url) {
options.url = $form.attr('action');
if (! options.url) {
options.url = window.location.href;
}
}
// Hi-jack form Submit
$form.bind('submit', function(event) {
// Prevents quick double submit
setTimeout(function() {
ajaxForm.submit()
}, 100);
return false;
});
this.options = $.extend({}, AjaxForm.options, options);
};
AjaxForm.options = {
msg_error: 'Your request cannot be processed at this time. The server is busy, please try again later.',
disable_session_lock : false, // Allow only one submit at a time
class_bad : 'bad',
class_good : 'good',
url : null,
data : {}, // Additional data to upload
timeout : 10000, // 10 seconds time out
ajax_upload : false, // enable file upload?
dataType : 'text', // Always text
type : 'POST', // Always post
buttons : [], // Array of clickable jquery elements in the form
// Define functions
error_renderer: renderError, // format error
busy_start: null,
busy_stop: null,
pre_validate: null, // Call before ajax submit
onSessionStart: onSessionStart,
onSessionEnd : onSessionEnd
};
/**
* See jQuery.ajax.success(data, textStatus, jqXHR)
*/
AjaxForm.prototype.success = function(data, status, xhr) {
if ($.isArray(data) || $.isPlainObject(data))
{
var returnedJson = data;
}
else
{
var returnedJson = $.parseJSON(data);
}
var errorList = returnedJson.error;
var isErrorFree = true;
for ( var index in errorList) {
var errors = errorList[index];
var container = null;
try {
container = this.$form.find('#' + index + '-container');
if (container.length == 0) {
container = this.$form.find('#' + index).parent();
}
if (errors && errors.length > 0) {
isErrorFree = false;
}
}
catch (ex) {}
container = (!container) ? this.$form : container;
var params = {
container: container,
errors: errors,
default_renderer: renderError,
index: index
};
this.options.error_renderer.apply(this, [params]);
}
// Only call custom sucess function if it free form error
if (this.options.custom_success && isErrorFree) {
this.options.custom_success(returnedJson);
}
else if (!isErrorFree && this.options.custom_error)
{
this.options.custom_error(errorList);
}
// Window redirect, we should keep buttons disabled
if (returnedJson.href) {
window.location.href = returnedJson.href;
var event = {success: true, keep_busy_on_success: true};
}
else {
var event = {success: true}; // Enable user to submit again
}
this.endSession.apply(this, [event]);
};
/**
* See jQuery.ajax.error(data, textStatus, jqXHR)
*/
AjaxForm.prototype.error = function(jqXHR, textStatus, errorThrown) {
if (this.options.custom_failure) {
this.options.custom_failure(jqXHR, textStatus, errorThrown);
}
else {
alert(this.options.msg_error);
}
this.endSession.apply(this, [{success: false}]);
};
/**
* Takes standard jQuery.ajax() options. Does the following:
*
* 1. Submit using jQuery for jQuery Form Upload
* 2. On success, trigger this.success() function
* 3. On timeout, trigger this.error() function
*
* @param options {} additional this.options override
*/
AjaxForm.prototype.submit = function(options) {
if (this.sessionTimeoutHandle) { // do nothing - prevents double submit
return;
}
if (options) {
options = $.extend({}, this, this.options, options);
}
else {
options = $.extend({}, this, this.options);
}
data = {}; // settings for $.ajax()
options.dataType = 'text'; // Lets submit text, jquery silently sollow parse error
options.type = 'POST'; // Post is best
options.success = this.success; // Can't let user override this function
options.error = this.error; // Can't let user override this function
options.context = this;
var errors = null;
this.startSession.apply(this, [{ajax_options: options}]); // Start up a session
if (options.pre_validate && $.isFunction(options.pre_validate)) {
errors = options.pre_validate.apply(this, [options]);
}
options.data = serialize(this.$form, data); // Re-init data
if ($.isPlainObject(errors) || $.isArray(errors))
{
this.success.apply(this, [errors]);
}
else {
// If we have ajaxSubmit library installed
if ($.fn.ajaxSubmit && options.ajax_upload) {
this.$form.ajaxSubmit(options);
}
else {
$.ajax(options);
}
}
return false;
};
/**
* Handles start of session
*
* 1. set timeout timmer to end session if ajax call takes longer than expected
* 2. diable input buttons so that user can not submit another
* 3. todo: show progress bar
* 4. Set input fields to readonly
*/
AjaxForm.prototype.startSession = function(event) {
var me = this;
if (!this.options.disable_session_lock) {
// Let session time out after specified timeout
this.sessionTimeoutHandle = setTimeout(function() {
me.endSession.apply(me, [{success: false}]);
}, this.options.timeout);
}
// Reset all errors
this.$form.find('.error').html('').css('display', 'none');
// Let delegate session Start
this.options.onSessionStart.apply(this, [event]);
this.$form.trigger('sessionStart', {options: this.options});
};
/**
* Handles start of session
*
* 1. kill timeout timmer
* 2. undo all the disable/readonly by startSession()
*
* @params keepSessionAlive sometime, it's useful to keep buttons and fields disabled, like
* setting window.location.href (It takes a while to load next page, and we want user to see
* progress bar)
*/
AjaxForm.prototype.endSession = function(event) {
// Request finished before our session end
if (this.sessionTimeoutHandle) {
clearTimeout(this.sessionTimeoutHandle);
}
this.options.onSessionEnd.apply(this, [event]);
this.$form.trigger('sessionEnd', event);
this.sessionTimeoutHandle = null;
};
/****************** jQuery Plugin starts here functions ******************/
var methods = {};
/**
* jQuery wrapper
*
* @param options
* @returns
*/
methods.init = function(options) {
return this.each(function() {
$this = $(this);
// If the element is not form element, continue on
if (this.tagName != 'FORM') {
return;
}
var ajaxForm = $this.data('ajaxform');
if (ajaxForm) {
return; // Already initailized
}
ajaxForm = new AjaxForm($this, options);
$this.data('ajaxform', ajaxForm);
});
};
methods.submit = function(options) {
return this.each(function() {
$this = $(this);
// If the element is not form element, continue on
if (this.tagName != 'FORM') {
return;
}
var ajaxForm = $this.data('ajaxform');
if (!ajaxForm) {
ajaxForm = new AjaxForm($this, options);
$this.data('ajaxform', ajaxForm);
}
ajaxForm.submit(options);
});
};
$.fn.ajaxForm = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else {
if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
}
else {
$.error('Method ' + method + ' does not exist on jQuery.ajaxForm');
}
}
};
// Allow override of default options
$.ajaxForm = function(options) {
AjaxForm.options = $.extend(AjaxForm.options, options);
};
})(jQuery);