xhrform.js - jscancer - Javascript crap (relatively small) | |
git clone git://git.codemadness.org/jscancer | |
Log | |
Files | |
Refs | |
README | |
LICENSE | |
--- | |
xhrform.js (2035B) | |
--- | |
1 function xhr_form_config(el) { | |
2 return { | |
3 "form" : el.form, | |
4 "fn" : window[el.getAttribute("data-xhr-status")], | |
5 "method" : el.getAttribute("data-xhr-method") || (el.for… | |
6 "action" : el.getAttribute("data-xhr-action") || (el.for… | |
7 "encoding" : el.getAttribute("data-xhr-encoding") || (el… | |
8 "timeout" : el.getAttribute("data-xhr-timeout") | |
9 }; | |
10 } | |
11 | |
12 function xhr_form_send(c, formdata) { | |
13 var x = new(XMLHttpRequest); | |
14 var encoding = c.encoding || "application/x-www-form-urlencoded"; | |
15 x.open(c.method || "get", c.action || "", true); // async | |
16 x.setRequestHeader("Content-Type", encoding); | |
17 x.setRequestHeader("X-Requested-With", "XMLHttpRequest"); | |
18 x.timeout = parseInt(c.timeout || "10000"); | |
19 x.onreadystatechange = function () { | |
20 if (x.readyState != 4) | |
21 return; | |
22 if (typeof(c.fn) == "function") | |
23 c.fn(x, formdata); | |
24 }; | |
25 var data = ""; | |
26 // FormData is normally sent as multipart encoded. | |
27 if (encoding === "application/x-www-form-urlencoded" ) { | |
28 var l = []; | |
29 for (var d of formdata.entries()) | |
30 l.push(d[0] + "=" + encodeURIComponent(String(d[… | |
31 data = l.join("&"); | |
32 } else { | |
33 data = formdata; | |
34 } | |
35 x.send(data); | |
36 } | |
37 | |
38 function xhr_form_submit(el) { | |
39 var d = new FormData(el.form); | |
40 d.append(el.name, el.value); // add submit button itself. | |
41 return xhr_form_send(xhr_form_config(el), d); | |
42 } | |
43 | |
44 /* initialize forms automatically on input submit which has a data-xhr a… | |
45 document.addEventListener("click", function(e) { | |
46 if (e.target === null || e.target.type !== "submit" || | |
47 e.target.tagName !== "INPUT" || | |
48 !e.target.form || e.target.getAttribute("data-xhr") === null) | |
49 return; | |
50 | |
51 if (e.target.form.noValidate || // disabled validation on form. | |
52 e.target.formNoValidate || // disabled validation on element. | |
53 !e.target.form.reportValidity || e.target.form.reportValidit… | |
54 xhr_form_submit(e.target); | |
55 | |
56 // prevent default action. | |
57 e.preventDefault(); | |
58 return !!e.stopPropagation(); | |
59 }, false); |