Ancora Imparo
Ancora Imparo

Reputation: 351

unable to email using EmailJS without alert

I am trying out EmailJS.com service with the following snippets: The HTML part:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Daily Report</title>
<script src="https://cdn.emailjs.com/dist/email.min.js"></script>
<script src="tst.js"></script>
<noscript>Please enable JavaScript.</noscript>
</head>
<body onLoad="today()">
<h1 id="today"></h1>
<hr>
<form onSubmit="draft()">
    <fieldset>
        <legend>Message</legend>
        <textarea id="shout" rows="2" cols="97">TEST.</textarea><br>
        <input type="submit" value="Email">
    </fieldset>
</form>
</body>
</html>

The JavaScript part:

var s = new Date().toDateString();
function today() {
    emailjs.init("EMAILJSASSIGNED");
    document.getElementById("today").innerHTML = s;
}
function draft() {
    var m = s + "<br>";
    m += document.getElementById("shout").value + "<br>";
    emailjs.send("EMAILJS_service", "TEMPLATE", {"body":m});
//alert(m);
}

I found that the code worked (ie, emailed according to my template specs) only if I add the alert(m) line. Seems like alert triggers a submit event to execute emailjs.send(). Without the alert, the emailjs.send is "skipped". I don't understand why.

Upvotes: 1

Views: 811

Answers (1)

Sasha
Sasha

Reputation: 1072

The reason the email is not sent without the alert is because once you submit the form the page is reloaded, and the browser doesn't have a chance to complete the emailjs.send() request.

One easy solution is to add "return false" to the onSubmit statement, as follows:

<form onSubmit="draft(); return false;">

That will prevent the form from being submitted though, so if you do need the form to be submitted to the server you'll need to do this asynchronously, after the promise returned by emailjs.send() is resolved.

You can read more on emailjs.send() syntax, with and without promises here: https://www.emailjs.com/docs/api-reference/emailjs-send/

Hope this helps!

Upvotes: 2

Related Questions