简体   繁体   中英

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:

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

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)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM