-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.html
81 lines (69 loc) · 2.29 KB
/
form.html
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
<!DOCTYPE html>
<html>
<h1> Submitting a form's data in JSON format using JS </h1>
<p>
Code:
<pre>
var form = document.getElementById('myform');
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function (response) {
console.log('response from server',response);
var responseHtml = document.getElementById('response');
responseHtml.innerHTML = response.target.response;
};
};
</pre>
</p>
<p>
<form action="https://jsonplaceholder.typicode.com/posts" method="post" id="myform">
Title: <input name="title" type="text" value="my title">
Body: <textarea name="body" value="my body"></textarea>
<input type="submit">
</form>
<pre id="response"></pre>
</p>
<footer>
<script>
var form = document.getElementById('myform');
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function (response) {
console.log('response from server',response);
var responseHtml = document.getElementById('response');
responseHtml.innerHTML = response.target.response;
};
};
</script>
</footer>
</html>