This repository was archived by the owner on Jul 1, 2019. It is now read-only.
forked from depuits/jQuery.AutoSaveForm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjQuery.auto-save-form.js
More file actions
70 lines (64 loc) · 1.82 KB
/
jQuery.auto-save-form.js
File metadata and controls
70 lines (64 loc) · 1.82 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
(function ($) {
$.fn.autoSaveForm = function (options) {
var settings = $.extend({
timeout: 1000,
fieldEvents : 'change keyup propertychange input',
fieldSelector: ":input:not(input[type=submit]):not(input[type=button])",
url: null
}, options); //TODO edit options
var initForm = function ($form) {
var timeoutId = 0;
var fields = $form.find(settings.fieldSelector);
$(fields).on(settings.fieldEvents, function (evt) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
save($form)
}, settings.timeout);
});
};
var sleep = function (milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
};
var save = function ($form) {
$.ajax({
url: settings.url ? settings.url : $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize() + '&isAjax=1', // serializes the form's elements.
beforeSend: function (xhr) {
// Let them know we are saving
var ret = $form.triggerHandler('beforeSave.autoSaveForm', [$form, xhr]);
if (ret === false) {
return false;
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 0) {
sleep(500);
}
$form.trigger('saveError.autoSaveForm', [$form, jqXHR, textStatus, errorThrown]);
},
success: function (data, textStatus, jqXHR) {
$form.trigger('saveSuccess.autoSaveForm', [$form, data, textStatus, jqXHR]);
},
});
};
return this.each(function (elem) {
var $form = $(this);
if (!$form.is('form')) {
return;
}
$form.submit(function (e) {
save();
e.preventDefault();
});
// Add a custom events
$form.on('save.autoSaveForm', function () { save($form); });
initForm($form);
});
};
}(jQuery));