'Post Form Using Fetch and Check Status OK
How does one get the reponse code when posting form data using fetch with vanilla JS, I have this code which posts but does not check response code with response.ok
<form method="post" id="form1" class="myForm" action="includes/vehicles/add-veh.php">
<input type="hidden" name="userid" id="userid" value="4448" />
<input type="hidden" name="vehid" id="vehid" value="84488" />
<button type="submit" name="submit" ><i class="fa-solid fa-circle-plus"></i> Save To Your List</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.myForm').addEventListener('submit', function (event) {
var data = this;
fetch(data.getAttribute('action'), {
method: data.getAttribute('method'),
body: new FormData(data)
})
.then(res=>res.text())
.then(function (data) {
})
.then((res) => {
if (response.ok) {
alert('success');
}
};
event.preventDefault();
});
});
</script>
Solution 1:[1]
This seems to work
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.myForm').addEventListener('submit',
function (event) {
var data = this;
fetch(data.getAttribute('action'), {
method: data.getAttribute('method'),
body: new FormData(data)
})
.then(function (response) {
if (response.ok) {
alert('success');
} else {
alert('error');
}
})
event.preventDefault();
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | donohoe |