POST Request Fetch API Prevent Redirect
So i want to make a pure html and javascript form and submit it to server. Here is my html form code:
Solution 1:
You're putting the .then
in the wrong place - put it right after the fetch
, not after the event listener.
var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
event.preventDefault()
fetch("", {
method: "POST",
body: new FormData(document.getElementById('email-signup'))
}).then((res) => {
if (res.ok) alert('Selamat email anda sudah terdaftar!')
})
})
Consistent indentation will help you avoid problems like this in the future. (see your question, I fixed the formatting - should be pretty clear what the problem was now)
Solution 2:
Possibly, you are putting JavaScript code before HTML and .then() after EventListner.
The solution will be to place JavaScript code after HTML and place .then() just after fetch.
<form id="email-signup" action="http://www.server.com" method="post">
<input id="firstname-input" type="hidden" name="firstname" value="">
<input type="text" name="email" placeholder="Input Email">
<input type="hidden" name="campaign[id]" value="1">
<input type="hidden" name="campaign[name]" value="Text Campaign">
<input type="submit" value="Submit">
</form>
<script>
var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
event.preventDefault()
fetch("", {
method: "POST",
body: new FormData(document.getElementById('email-signup'))
}).then(() => {
alert('Selamat email anda sudah terdaftar!')
})
})
</script>
Post a Comment for "POST Request Fetch API Prevent Redirect"