]> dev.renevier.net Git - syj.git/blob - public/js/ajaxize.js
version 0.1
[syj.git] / public / js / ajaxize.js
1 /*  This file is part of Syj, Copyright (c) 2010 Arnaud Renevier,
2     and is published under the AGPL license. */
3
4 // wrapper around Form.request that sets up the submit listener, stops the
5 // submit event, calls presubmit function, calls Form.request and calls a
6 // postsubmit function
7 Element.addMethods('form', {ajaxize : function(form, options) {
8     var reqoptions, timeout;
9
10     options = Object.clone(options);
11     reqoptions = Object.clone(options);
12     timeout = null;
13
14     function onSuccess(transport, json) {
15         if (timeout) {
16             window.clearTimeout(timeout);
17             timeout = null;
18         }
19         if (transport.getStatus() === 0) {
20             options.onFailure(transport, json);
21         } else {
22             options.onSuccess(transport, json);
23         }
24     }
25
26     function onFailure(transport, json) {
27         if (timeout) {
28             window.clearTimeout(timeout);
29             timeout = null;
30         }
31         options.onFailure(transport, json);
32     }
33
34     delete(reqoptions.presubmit);
35     delete(reqoptions.postsubmit);
36
37     $(form).observe('submit', function(evt) {
38         var req;
39
40         evt.stop(); // cancel form submission
41         if (Object.isFunction(options.presubmit)) {
42             if (options.presubmit(this) === false) {
43                 return;
44             }
45         }
46         req = this.request(Object.extend(reqoptions, {
47             onSuccess: onSuccess,
48             onFailure: onFailure
49         }));
50         timeout = (function() {
51             options.onFailure(null);
52             req.abort();
53         }).delay(options.timeout || 20);
54         if (Object.isFunction(options.postsubmit)) {
55             options.postsubmit(this);
56         }
57     });
58 }});