Home > database >  How to prevent html form refresh on submit?
How to prevent html form refresh on submit?

Time:07-19

Hello after searching and trying a lot , i am not able to find the issue so that I am seeking your help to solve my issue.

Here I have a form while clicking on submit button it should call the javascript function and should not redirect or refresh the page .

Here I want to send mail using SMTPJS with attachments by filling the form and choosing the image once the form submitted it should call the sendEmail() function and mail should be send, but when i click on the submit button it's refreshing the page and it's not working accordingly.

<form onsubmit="sendEmail(); reset(); return false">
          <div >
              <div >
                  <input type="file"  id="fileupload" required>
      <label for="phone">Upload file</label>
               </div>
         </div>
                                        
         <div >
             <button  type="submit" style="background-color: #0e2e50;">Upload</button>
     </div>
      </div>
    </form>

    <script>
            function sendEmail() {
                var file = event.srcElement.files[0];
       var reader = new FileReader();
       reader.readAsBinaryString(file);
       reader.onload = function () {
           var dataUri = "data:"   file.type   ";base64,"   btoa(reader.result);
                Email.send({
                    Host: "smtp.elasticemail.com",
                    SecureToken :"************"
                    To: '[email protected]',
                    From: "[email protected]",
                    Subject: "Form Enquiry",
                    Body : "Sending file:"   file.name,
                        Attachments : [
                {
                    name : file.name,
                    data : dataUri
                }]
                }).then(
                    message => alert(message)
                );
            };
            }
        </script>

I think the issue is in this line 'var file = event.srcElement.files[0];' because from this line it's refreshing the page and a Question mark (?) is coming in the URL. ex.page.html?

One more thing if i am calling the sendEmail() function in the onchange event of the input type file then it's working fine, why so?

CodePudding user response:

You have two problems.

Typo

The first is a typo and is highlighted by the browser telling you:

Uncaught SyntaxError: missing } after property list note: { opened at line 24, column 19

This exception is preventing the function from being created, so the onsubmit function errors when it calls it, and you never reach the return false that prevents the form submission.

Read the error messages in the console in the browser developer tools.

You are missing a comma between SecureToken :"************" and To: '[email protected]'.

Forms don't have files

You said:

var file = event.srcElement.files[0];

Which gets the element that triggered the event (since it is a submit event, that is the <form>) and you try to read the files property from it.

The browser tells you this:

Uncaught TypeError: event.srcElement.files is undefined

Read the error messages in the console in the browser developer tools.

The files property can be found on <input type="file">, not on the <form>.

You need to find the correct element:

var file = event.srcElement.querySelector('[type="file"]').files[0];

Asides

To generally make life easier and avoid these sorts of issues:

  • Use a linter, like ESLint, and an editor that can use it as a plug in
  • Use a code formatter to indent code and help locate syntax errors
  • Don't use intrinsic event attributes (like onsubmit); do use addEventListener
  • Pay attention to what your debugging tools are telling you

CodePudding user response:

Just change it a little bit:

<form onSubmit="sendEmail(event)">
...
</form>

function sendEmail(event) {
  event.preventDefault();
  ...
}
  • Related