Submit Form Using Fetch API

PHOTO EMBED

Tue Aug 01 2023 12:11:52 GMT+0000 (Coordinated Universal Time)

Saved by @ryanc713 #fetch #fetch_api #form_submit #formdata #json #json.stringify

document.getElementById('myForm').addEventListener('submit', function(event) {
  event.preventDefault();

  const formData = new FormData(this);

  const jsonObject = {};
  formData.forEach(function(value, key) {
    jsonObject[key] = value;
  });

  fetch('your-php-script.php', {
    method: 'POST',
    body: JSON.stringify(jsonObject),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error('Error:', error);
  });
});
content_copyCOPY