Answers for "fetch post with form data"

35

js fetch 'post' json

//Obj of data to send in future like a dummyDb
const data = { username: 'example' };

//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then((response) => response.json())
//Then with the data from the response in JSON...
.then((data) => {
  console.log('Success:', data);
})
//Then with the error genereted...
.catch((error) => {
  console.error('Error:', error);
});

//																		Yeah
Posted by: Guest on March-28-2020
-2

submit formdata in fetch

// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');

fetch("api/SampleData",
    {
        body: formData,
        method: "post"
    });
Posted by: Guest on March-23-2020
-1

fetch post form data

// It's almost copy paste ajax function,
// just select the right Form and set the right URL

document.getElementById('submitBtn').onclick = ajax

function ajax(e){
	e.preventDefault()

	// Get form element and create a formData object
	const form = document.getElementsByTagName('form')[0]
	const formData = {}

	// Get all input elements inside a form
    // and create key:value pairs inside formData
	form.querySelectorAll('input').forEach(element => {
		formData[element.name] = element.value
	})

	// Send data to your backend
	fetch(url, {
		method: "POST",
    	headers: {
    		"Content-Type": "application/json"
    	},
    	body: JSON.stringify(formData)
	})
}
Posted by: Guest on July-28-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language