javascripthtmlformssubmit-button

Action on document.getElementById is not redirecting me to created upload link


I have an HTML page where users choose files and upload them to a URL through pressing a submit button. This button redirects the user to the URL while also submitting the file to the URL. Currently, however, my page is not redirecting to the upload URL and only stays on the original HTML page, not submitting anything. I was considering removing e.preventDefault and return false from submitForm however they are needed for the code to function. What should I do?

HTML snippet:

<form method = "post" enctype="multipart/form-data" id = finalsubmit onsubmit = "submitForm(event)">
    <label for = "myfile"><strong>Select a file to be uploaded:</strong></label>
    <input class = choosebutton type = "file" id = "myfile" name = "filename"><br>
    <input class = uploadbutton type = "submit" onclick="finalSubmission()" value = "Upload File">
</form>

Javascript snippet:

async function finalSubmission () {
    const accessKey = await assignSas(); // function to develop key
    let urlFinal = "https://<upload-link> + "?accesskey=" + accessKey;
    document.getElementById("finalsubmit").action = urlFinal;
}

async function submitForm(e) {
    e.preventDefault();
    await Promise.resolve();
    return false
}

Solution

  • When you call the functions with onclick it doesn't await the functions. So if you use asynchronous code to change the action of the form, the form will be submitted before it finishes.

    Using e.preventDefault() just prevents the form from being submitted automatically at all.

    What you should do is update the action and then call form.submit() explicitly. You can do it all in one function.

    async function finalSubmission(e) {
      e.preventDefault();
      const accessKey = await assignSas(); // function to develop key
      let urlFinal = `https://<upload-link>?accesskey=${accessKey}`;
      e.target.action = urlFinal;
      e.target.submit();
    }
    <form method="post" enctype="multipart/form-data" id="finalsubmit" onsubmit="finalSubmission(event)">
      <label for="myfile"><strong>Select a file to be uploaded:</strong></label>
      <input class="choosebutton" type="file" id="myfile" name="filename"><br>
      <input class="uploadbutton" type="submit"" value="Upload File">
    </form>