1

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 class="col-md-12">
              <div class="form-floating">
                  <input type="file" class="form-control" id="fileupload" required>
      <label for="phone">Upload file</label>
               </div>
         </div>
                                        
         <div class="col-12">
             <button class="btn btn-primary w-100 py-3" 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: 'mail@mail.com',
                    From: "mail@mail.com",
                    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?

Pallab
  • 53
  • 1
  • 6
  • 1
    Does this answer your question? [Stop form refreshing page on submit](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) – Matthew Herbst Jul 19 '22 at 04:24
  • No, preventDefault() is not working in my case @MatthewHerbst – Pallab Jul 19 '22 at 05:14
  • `onsubmit="sendEmail(); reset(); return false"` — The `return false` should block regular form submission (and thus page reloading) unless the JS throws an exception. Have you checked the browser console to see if it does? – Quentin Jul 19 '22 at 07:25
  • @Quentin there is an error in the console "Uncaught TypeError: Cannot read properties of undefined (reading 'srcElement')" this line -> var file = event.srcElement.files[0]; – Pallab Jul 19 '22 at 07:38

2 Answers2

1

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: 'mail@mail.com'.

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
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Just change it a little bit:

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

function sendEmail(event) {
  event.preventDefault();
  ...
}
  • 1
    That will throw an exception because `event` is `undefined`. – Quentin Jul 19 '22 at 07:03
  • @Quentin By adding the `event` as a parameter when you are calling the function you can define it – Sepehr Amirkiaee Jul 19 '22 at 07:17
  • Yes, but your answer (before you edited it) didn't do that. After editing, your answer is now effectively the same as [this older one](https://stackoverflow.com/a/73031525/19068) except you are reading the global event variable in a different place and passing it. – Quentin Jul 19 '22 at 07:19
  • Well, yes, I said it was the same as the previous answer, not that it wouldn't work. – Quentin Jul 19 '22 at 07:21
  • @SepehrAmirkiaee if i am adding event.preventDefault() its stop refreshing but it not able to read this line 'var file = event.srcElement.files[0];' i put a alert after this line its not working and the mail is not getting sent – Pallab Jul 19 '22 at 07:28