Answers for "fetch post data in javascript"

19

fetch json post

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();
Posted by: Guest on May-07-2020
1

how to post data using fethch

fetch('url here', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
    body: 'foo=bar&blah=1'
});
Posted by: Guest on September-19-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