tohhy
tohhy

Reputation: 145

How to use Fetch API to retrieve and send data from form?

I have html form:

<form action="file.php" method="post">
    <input name="formName" type="text" />
    <input name="formEmail" type="email" />
    <input name="formSubmit" type="submit" value="Submit Me!" />
</form>

So how to use Fetch API in order to get those values and send them to file.php file using ajax?

Upvotes: 4

Views: 9067

Answers (3)

Nandini_23
Nandini_23

Reputation: 11

const formSubmit = {
  const sendData = {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      'name': 'name',
      'email': '[email protected]'
    })
  }
  fetch('url',sendData)
  .then(resp => resp.json())
  .then(data => console.log('Data',data)
  }
}

Upvotes: -1

Zolt&#225;n S&#252;le
Zolt&#225;n S&#252;le

Reputation: 1704

I would recommend to use FormData. It uses the same format a form would use if the encoding type were set to "multipart/form-data". More details about it.

    const submitForm = () => {
        const formEl = document.getElementById('formId');
        const payload = new FormData(formEl);

        fetch('file.php', {
            method: 'POST',
            body: payload,
        })
        .then(Result => Result.json())
        .then(data => {
            console.log(data);
            // your code comes here
        })
        .catch(errorMsg => {
            console.log(errorMsg);
        });

    };

Upvotes: 0

Muthu Kumaran
Muthu Kumaran

Reputation: 17920

Using Fetch API

function submitForm(e, form){
    e.preventDefault();
    
    fetch('file.php', {
      method: 'post',
      body: JSON.stringify({name: form.formName.value, email: form.formEmail.value})
    }).then(function(response) {
      return response.json();
    }).then(function(data) {
      //Success code goes here
      alert('form submited')
    }).catch(function(err) {
      //Failure
      alert('Error')
    });
}
<form action="file.php" method="post" onsubmit="submitForm(event, this)">
    <input name="formName" type="text" />
    <input name="formEmail" type="email" />
    <input name="formSubmit" type="submit" value="Submit Me!" />
</form>

Upvotes: 6

Related Questions