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: newFormData(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.
<formid="email-signup"action="http://www.server.com"method="post"><inputid="firstname-input"type="hidden"name="firstname"value=""><inputtype="text"name="email"placeholder="Input Email"><inputtype="hidden"name="campaign[id]"value="1"><inputtype="hidden"name="campaign[name]"value="Text Campaign"><inputtype="submit"value="Submit"></form><script>var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
event.preventDefault()
fetch("", {
method: "POST",
body: newFormData(document.getElementById('email-signup'))
}).then(() => {
alert('Selamat email anda sudah terdaftar!')
})
})
</script>
Post a Comment for "Post Request Fetch Api Prevent Redirect"