Home > other >  How to prevent page from refreshing after JavaScript fetch post request?
How to prevent page from refreshing after JavaScript fetch post request?

Time:12-23

I'm sending a file from the client to a Flask API. I've tried doing e.preventDefault(), e.stopPropagation(), and return false for "onsubmit" on the form, but it still refreshes the page I need the web to hold onto some information the API will send back but it disappears after the page refreshes. I've tried using local storage to store the data but it goes away when the page refreshes. Sorry if its a stupid question :pray:

Javascript

const form = document.querySelector("#upload-form");
const uploadBtn = document.querySelector("#upload-btn");
const uploadInp = document.querySelector("#upload-input");

const sendFile = async () => {
  let formData = new FormData();
  formData.append("file", uploadInp.files[0]);
  await fetch(apiPOST, {
    method: "POST",
    body: formData,
  })
    .then((res) => res.json())
    .then((json) => {
      console.log(json);
    })
    .catch((err) => console.log(err));
};

uploadBtn.addEventListener("click", (e) => {
  e.preventDefault();
  sendFile();
});

HTML

<form id="upload-form" enctype="multipart/form-data" method="post" onsubmit="return false">
     <label for="upload-input" >Upload File</label>
     <input type="file" id="upload-input" name="upload-input" accept=".pptx"/>
     <!-- <button id="upload-btn">Upload</button> -->
     <input type="submit" id="upload-btn" value="Upload" />
</form>

CodePudding user response:

You should call the preventDefault method from the form submit attribute, not your button.

Check this answer for more info

  • Related