POST request Fetch API prevent redirect

好久不见. 提交于 2021-02-10 17:48:43

问题


So i want to make a pure html and javascript form and submit it to server.

Here is my html form code:

<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>

And here is my javascript code:

var element = document.getElementById("email-signup");
element.addEventListener("submit", function(event) {
  event.preventDefault()
  fetch("http://www.endpoint.api", {
    method: "POST",
    body: new FormData(document.getElementById('email-signup'))
  })
})
  .then(() => {
  alert('Selamat email anda sudah terdaftar!')
})

The problem is, whenever i submit an email to that form it redirects me to a new page with a response of success. I want to prevent that to happen and instead it will pop up an alert that tells me the email submission is succeeded.


回答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)




回答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>


来源:https://stackoverflow.com/questions/49663596/post-request-fetch-api-prevent-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!