简体   繁体   中英

POST Fetch request causing page to reload using javascript and submit form with prevent default

im working on a rails API + Javascript project, with a simple form on html. Everytime I hit the submit button, all my code is executed but then the browser page reloads.

Here is the HTML code:

<form id="create-player">
        <h3>Enter Your Name</h3>
        <input
          type="text"
          name="name"
          value=""
          placeholder="Enter your name..."
          class="input-text"
        />
        <br />
        <input
          type="submit"
          name="submit"
          value="SUBMIT"
          class="submit"
        />
      </form>

Then my js code:

document.addEventListener("DOMContentLoaded", () => {
    //submit form action
    player_form.addEventListener("submit", function(a){
        a.preventDefault();
        console.log('submit pressed')
        fetchNewPlayer(a.target.name.value);
      });
})
function fetchNewPlayer(name){
    console.log('start fetch')
    let formData = {
        name: name
    }
    let configObj = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json"
      },
      body: JSON.stringify(formData)
    };

    fetch('http://localhost:3000/players', configObj)
    .then(function(response) {
        console.log('fetching', response);
        return response.json();
   
    })
    .then(function(object) {
        console.log('then', object);
        
    })
    .catch(function(error) {
        console.log('failed', error);
        alert("Error");
    });
  }

Crazy part is, that if I comment the fetchNewPlayer, the page doesnt reloads. Can someone help me understand whats wrong?

You need to use an AbortController :

let abortController = new AbortController();

let configObj = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json"
  },
  body: JSON.stringify(formData),
  signal : abortController.signal
};

window.onbeforeunload = function(e) { abortController.abort(); };
fetch('http://localhost:3000/players', configObj)
...

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