Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
tohhy Avatar asked Sep 20 '25 00:09

tohhy


1 Answers

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>
like image 101
Muthu Kumaran Avatar answered Sep 21 '25 13:09

Muthu Kumaran