1//Obj of data to send in future like a dummyDb
2const data = { username: 'example' };
3
4//POST request with body equal on data in JSON format
5fetch('https://example.com/profile', {
6 method: 'POST',
7 headers: {
8 'Content-Type': 'application/json',
9 },
10 body: JSON.stringify(data),
11})
12.then((response) => response.json())
13//Then with the data from the response in JSON...
14.then((data) => {
15 console.log('Success:', data);
16})
17//Then with the error genereted...
18.catch((error) => {
19 console.error('Error:', error);
20});
21
22// Yeah
1async function postData(url = '', data = {}) {
2 // Default options are marked with *
3 const response = await fetch(url, {
4 method: 'POST', // *GET, POST, PUT, DELETE, etc.
5 mode: 'cors', // no-cors, *cors, same-origin
6 cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
7 credentials: 'same-origin', // include, *same-origin, omit
8 headers: {
9 'Content-Type': 'application/json'
10 // 'Content-Type': 'application/x-www-form-urlencoded',
11 },
12 redirect: 'follow', // manual, *follow, error
13 referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
14 body: JSON.stringify(data) // body data type must match "Content-Type" header
15 });
16 return response.json(); // parses JSON response into native JavaScript objects
17}
18
19postData('', )
20 .then(data => {
21 console.log(data); // JSON data parsed by `data.json()` call
22 });
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((myJson) => {
6 console.log(myJson);
7 });
1// Build formData object.
2let formData = new FormData();
3formData.append('name', 'John');
4formData.append('password', 'John123');
5
6fetch("api/SampleData",
7 {
8 body: formData,
9 method: "post"
10 });
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((data) => {
6 console.log(data);
7 });
8
1// It's almost copy paste ajax function,
2// just select the right Form and set the right URL
3
4document.getElementById('submitBtn').onclick = ajax
5
6function ajax(e){
7 e.preventDefault()
8
9 // Get form element and create a formData object
10 const form = document.getElementsByTagName('form')[0]
11 const formData = {}
12
13 // Get all input elements inside a form
14 // and create key:value pairs inside formData
15 form.querySelectorAll('input').forEach(element => {
16 formData[element.name] = element.value
17 })
18
19 // Send data to your backend
20 fetch(url, {
21 method: "POST",
22 headers: {
23 "Content-Type": "application/json"
24 },
25 body: JSON.stringify(formData)
26 })
27}