0

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" class="btn">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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Luth Andyka
  • 3
  • 1
  • 2

3 Answers3

0

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

Check this answer for more info

Ako
  • 197
  • 1
  • 13
0

I had this same issue, in my case the problem was caused by the live server. I had in the same folder the client (HTML,CSS, JS, etc.) and the database (I was using the json-server extension). The problem was that the live server was detecting the changes in the db.json file. When fetch post or delete data, it triggers the live reload in the live server extension. So I solved it by dividing the folders and opening them separately in vs code, then, inside the client folder, run live server and it worked perfectly.

--Edit--

Some people asked for code examples. The thing is I don´t have any. I can tell you how I discovered this "bug". Instead of using the live server visual studio code extension, I used the npm version, wich, as far as I know, it's the extension that the visual studio code live server use. there you can see each request and each change of the files in he folder. There you can see that the live server extension detects each change in the database and reloads the page. Screenshot with live server "bug" If you look at the bottom, you can see that live server detects the change in the database as a change in the folder, you can solve this by putting the database outside the folder where you have the frontend. Screenshot without live server "bug" Now that the database folder is outside the frontend folder (Alura_geek(e-commerce)-database) you can see that live server doesn't detects the changes in the db.json file (database) and doesn't reloads the page

  • Add the code saamples also here, to make the answer more clear – Matteo Possamai Oct 01 '22 at 07:20
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 01 '22 at 07:20
  • more details here reference not linked. – ruud Oct 04 '22 at 09:54
-1

I had the same isue like Ulises Rodriguez and he sved my day :D In my case it realy cause LiveServer plugin in VSCode (it detected log json which is genenerated by BE). When I turned it off preventDefault() function start working and page stop reloading after form POST. Here is code example:

    dbUploadForm.addEventListener('submit', async function(upload) {
    upload.preventDefault();

        const postData = new FormData(this);
        const jsonData = JSON.stringify({
            sheet: sheet.value,
            headerRow: headerRow.value,
            dataStartRow: dataStartRow.value,
            databaseTable: selectdatabaseTable.getValue(),
            tableType: tableType.value,
            pageName: pageName.value
        });
        postData.append('jsonData', jsonData);
        postData.append('userFile', userFile.files[0]);

        const response = await fetch(API.admin.file.uploadExcelToDb, {
                method: 'POST',
                headers: {
                    'credentials': 'same-origin',
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: postData
            })
            .then((response) => response.json())
            .then((data) => {
                if (data) {
                    buttonEnableHideSpinner(id("uploadButton"));
                }
                if (data['status'] === 200) {
                    let validationAlert = new Alert({
                        message: data['message'],
                        displayInElement: id('alerts'),
                        result: 'success',
                        id: 'validationAlert'
                    }).show()
                } else {
                    let validationAlert = new Alert({
                        message: data['message'],
                        displayInElement: id('alerts'),
                        result: 'danger',
                        id: 'validationAlert'
                    }).show()
                }
            });

}, false);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Loxio
  • 1
  • 3