-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax.html
50 lines (48 loc) · 1.4 KB
/
ajax.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Alpine AJAX request</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<!-- Alpine.js -->
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>
<body>
<main>
<p>Value from input is send to API through AJAX (fetch), response is received and printed.</p>
<form
x-data="{
form: {
name: ''
},
user: null,
submit() {
<!-- Standard fetch using POST to a fake API -->
fetch('https://reqres.in/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.form)
})
.then(response => response.json())
.then(user => this.user = user);
}
}"
@submit.prevent="submit"
>
<div>
<label for="name">Name</label>
<input type="text"
name="name"
id="name"
x-model="form.name"
required
>
</div>
<template x-if="user">
<div x-text="'The user ' + user.name + ' was created.'"></div>
</template>
</form>
</main>
</body>
</html>