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?
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?
Share Improve this question asked Jul 28, 2017 at 9:44 tohhytohhy 1451 gold badge3 silver badges11 bronze badges 5- Take a look at this page here: scotch.io/tutorials/… – Fotis Grigorakis Commented Jul 28, 2017 at 9:49
- @FotisGrigorakis thanks, but I need an exact example with form and php. – tohhy Commented Jul 28, 2017 at 9:55
- you can follow the steps from the site i wrote and do it your way. ;) – Fotis Grigorakis Commented Jul 28, 2017 at 9:57
- @FotisGrigorakis In your link there's no example of sending data from a form using fetch – Madacol Commented Oct 1, 2019 at 14:16
- What have you tried so far? Where are you stuck? How is this problem related to PHP itself? – Nico Haase Commented Jan 12, 2024 at 8:36
3 Answers
Reset to default 6Using 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>
I would remend 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 es here
})
.catch(errorMsg => {
console.log(errorMsg);
});
};
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)
}
}