0

I'm uploading a file with fetch(), and when the upload is finished, call fetch() again to add or amend a MariaDB row. When I upload a file and add the row, it works. When I upload a file and amend the row, the file is uploaded but the 2nd fetch() is not called, and the page just reloads.

This is the code that does both tasks

var form_data = new FormData();
form_data.append('file', file_data);

fetch('upload.php', {
    method: 'POST',
    body: form_data
})
.then(response => response.text())
.then(data => {
    console.log("data in fileUpload:", data);
    itemUpdate ( toPostObj, data )    })  // add or amend the row data
.catch(error => {
    console.error(error)
})

This seems so self-contained in that scrap of code that I can't see how it can bypass both console logs. Whether the file upload terminates correctly or with an error, it has to write to the console. Or so I thought.

When adding a file and row, it does so. The console shows

"data in fileUpload: The file 5.jpg has been uploaded."

But when adding a file and amending a row, it uploads the file, and reloads the page, showing this:

Navigated to http://192.168.0.104/t3/journal.html?chooseFile2=6.jpg&fileDisp=keepFile

Add and amend use different forms on the web page. They both use type=button, not <input type="submit"> and pressing a button triggers the appropriate event listener. itemUpdate() does another fetch() to access the database and is never executed. It starts with a console.log statement which never appears.

upload.php writes to a log file on the server and the debug logging in that has messages that confirm this operated as expected. The file is uploaded. Finally, the apache2 php error.log is empty.

I have access to the server.

I've been looking at this all day. Where am I going wrong?

Thanks.

Roy Grubb
  • 93
  • 2
  • 11
  • 1
    Clicking the button probably submits the form it's attached to, **refreshing the page**…!? You need to `preventDefault` if you're handling a form submission via Javascript… – deceze Jan 01 '21 at 18:14
  • Thank you very much, that was it. Some how I'd got it linked in my mind to avoiding type=submit in the HTML. Please make this an answer so I can flag it as such. – Roy Grubb Jan 02 '21 at 06:52
  • It has been suggested that this is the same as https://stackoverflow.com/questions/7803814/prevent-refresh-of-page-when-button-inside-form-clicked but that assumes that I knew that the problem lay with the button. I didn't, and to me the problem seemed to be understanding how a fetch() could bypass its success and error logic. I agree the answer is the same, but I started with a different point of ignorance, and if I'd seen that question, I wouldn't have seen that it was relevant. – Roy Grubb Jan 02 '21 at 15:24

0 Answers0