unable to email using EmailJS without alert - javascript

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.

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!

Related

Firefox Latest Update - Javascript Issue

I am using a third party software which uses the Prototype library. It was working fine before the latest update (Ver 68 and above) of Firefox. It is still working in the other browsers. I tried debugging and whenever I introduce a breakpoint and go step by step the code works. I found the following line of code which if I step over and let the code run the problem is solved. But if I let the code run before this the problem occurs.
return formView.submit();
Any idea? I am ok with a hack even.
Update:
I created a MRE as suggested. Here is the link https://brandsoftinfotech.com/test/firefox-frame-submit/
I have created 2 forms, one in the parent page and one in the frame. On submitting the parent page form the frame page form gets submitted and writes the data in a log file. And the form page when submitted just shows the data from that log file.
index.html
<!DOCTYPE html>
<html>
<head>
<script>
function submitFunction() {
var myFrame = document.getElementById("myFrame");
var myForm = myFrame.contentWindow.document.getElementById("myForm");
myForm.submit();
}
</script>
</head>
<body>
<form action="index-submit.php" onSubmit="submitFunction()">
<input type="submit" value="Submit">
</form>
<iframe id="myFrame" src="frame-box.html"></iframe>
</body>
</html>
frame-box.html
<form action="frame-submit.php" id="myForm">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
</form>
This works fine on Chrome, MS Edge but doesn't work on Firefox.
I am not sure if solving this would solve my problem, but at least this should work for my library code to work.
I'm mildly surprised to see that it works on any browser. By allowing the parent's form submission to occur, you're tearing down the page, which means tearing down the iframe, and any requests that may be underway can be aborted (or if not quite started, never started).
I'd probably switch to ajax rather than doing the actual form submission.
But if you want to do the form submission, to do this reliably you'll have to wait for the frame's submission to complete before doing the parent submission. The easy way to do that is to have the frame submission respond with a small page with JavaScript on it that tells the parent it's finish:
<!DOCTYPE html>
<html>
<body>
<script>
if (parent && parent.formCallback) {
parent.formCallback();
}
</script>
</body>
</html>
Then the parent page is something like:
<!DOCTYPE html>
<html>
<head>
<script>
function submitFunction() {
var myFrame = document.getElementById("myFrame");
var myForm = myFrame.contentWindow.document.getElementById("myForm");
myForm.submit();
return false; // <−−−−−−−− cancel submission
}
function formCallback() { //
document.getElementById("parentForm").submit(); // <−−−−−−−− Submit on callback
} //
</script>
</head>
<body>
<!-- vvvvvvvvvvvvvvv−−−−−−−− Added ID -->
<form id="parentForm" action="/index-submit" onSubmit="return submitFunction()">
<input type="hidden" name="index-field" value="x">
<input type="submit" value="Submit">
</form>
<iframe id="myFrame" src="frame-box.html"></iframe>
</body>
</html>
But you may get away with just detecting the change in location in the iframe. That would involve just changing the parent page as indicated:
<!DOCTYPE html>
<html>
<head>
<script>
function submitFunction(form) { // <−−−−−−−− Added parameter
var myFrame = document.getElementById("myFrame");
var myForm = myFrame.contentWindow.document.getElementById("myForm");
myForm.submit();
// Wait for the location of the iframe window to change
setInterval(function() {
if (String(myFrame.contentWindow.location).includes("frame-submit")) {
// Frame's form submitted, we can submit ours
form.submit();
}
}, 100);
return false; // <−−−−−−−− cancel submission
}
</script>
</head>
<body>
<form action="/index-submit" onSubmit="return submitFunction(this)">
<!-- ^^^^−−−−−−−−− added argument -->
<input type="hidden" name="index-field" value="x">
<input type="submit" value="Submit">
</form>
<iframe id="myFrame" src="frame-box.html"></iframe>
</body>
</html>
I wouldn't expect that to work if the form in the frame does a significant upload (though I could be wrong about that).

Use JavaScript to automatically fill in HTML forms

I'm trying to automate a test routine in a web application. My goal is to fill forms, submit them and get the html returned by the application after the form is submited. In other words, i want to simulate what a human would do, but as i need to do this in dozens of forms, i want to do it automatically using pure JS (no frameworks).
For instance, a login form i'm trying to submit looks like this :
To fill the form i'm using a code like this :
document.getElementById('username').value = 'test#test.com';
document.getElementById('password').value = 'mypassord';
But it seems the information is not being correctly filled ; after i run the code above, the form looks like this :
As you can see, the placeholder is still on the inputs and if i submit the form, the input values are not submited. It seems the 'value = 'xxx'' is not effectively filling the field.
It only works if i manually input something on the keyboard after running the code above.
What else can i try ?
Thanks !
Here is the complete code. Run on your browser hope it will works for you.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" placeholder="This is text Field" id="txtField">
<input type="password" placeholder="Input password" id="txtPass">
<script>
document.getElementById('txtField').value = 'test#test.com';
document.getElementById('txtPass').value = 'test#123';
</script>
</body>
</html>

Javascript ES6: setting <h1> with local storage and form submission

I am trying to set the element #welcome_banner by using a function in javascript that takes a form submission and sets it to localStorage and then pulls that info and sets it onto an <h1> tag. Apparently it works but only changes the tag for a millisecond and then it disappears! I have tried doing the .innerHTML setting in various places inside and outside of the function clickHandler() and in the main body of the script. I am certain this is something superbasic I am missing.
<!DOCTYPE html>
<html>
<head>
</head>
<script >
//set display name to form submission, set welcome banner to display name
function clickHandler () {
document.querySelector('#display_name').onsubmit = function() {
localStorage.setItem('dn', dn);
document.querySelector('#welcome_banner').innerHTML=changeWelcomeBanner;
}
};
function changeWelcomeBanner () {
var dn = localStorage.getItem('#dn').value;
var welcomeBanner = document.getElementById('#welcome_banner');
welcomBanner.innerHTML = `Hello ${dn}`;
}
</script>
<title>Project 2</title>
<body style="background-color:#ff3300;">
<h1 id="welcome_banner"></h1>
<form id="display_name">
<input id="dn" autocomplete="off" autofocus placeholder="" type="text">
<button>set display name</button>
</body>
</html>
The steps to do this are as follows:
Store the typed text in localStorage, you're doing this in the event handler for the form submission: localStorage.setItem('dn', dn);
When you submit the form, the page is going to refresh from the server. This is why you're only seeing the text briefly, then the page reloads from the server with no knowledge of what was there before.
Look for information about page events and write a handler for the DOMContentLoaded event like you did for your submit event handler. DOMContentLoaded is well supported these days. Something like: document.addEventListener("DOMContentLoaded", function(event) {
// code to check local storage goes here...
});
In that handler you want to check localStorage like you're doing here: var dn = localStorage.getItem('dn').value; and if there is a value there, set the innerHtml of the <h1> to that value, like you're doing here: welcomBanner.innerHTML = 'Hello ${dn}';
I think you might have had a stray # character in your localStorage.getItem call that I removed in the steps above. You might also want to have default text you post if there's nothing found in localStorage when you check.
Here's a simplified example:
If you are calling a function to get the value from Local Storage, be sure you have a return
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1 id="welcome"></h1>
<input type="text" id="something">
<button type="button" id="click">CLICK ME</button>
<script>
document.getElementById("click").addEventListener("click", function(){
var x=document.getElementById("something").value;
document.getElementById("welcome").innerHTML=x;
localStorage.setItem('x', JSON.stringify(x));
document.getElementById("welcome").innerHTML = getData();
});
function getData(){
var retrieve=localStorage.getItem('x');
return JSON.parse(retrieve); //Now return the value
}
</script>
</body>
</html>

JavaScript redirect just before submitting form and opening new tab

I have a situation where I need to open a new tab to an external site when the user clicks "submit" on a form, and at the same time I need to redirect the original tab to a different page to prevent the user making multiple duplicate requests to the external site.
NOTE: I have protected against this behaviour in the back-end, I just want to use JavaScript to improve the UX where possible, removing the rendering of the option in the first place.
NOTE2: This works in Firefox, but not in Chrome or Safari.
Some example code which illustrates my issue is shown below:
<script type="text/javascript">
function testFunction(){
alert("Executing testFunction()!");
window.location.replace("http://www.google.com");
}
// uncomment this line to show that testFunction() does work when called directly
//testFunction();
</script>
<html>
<head>
<title>JS Redirect Then Post Test</title>
</head>
<body>
<form action="" method="POST" target="_blank">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br><br>
<input type="submit" value="Submit" onclick="testFunction()">
</form>
</body>
</html>
When I click submit, I observe the alert popping up, but the redirect does not execute.
If I uncomment the line which calls testFunction() directly, it works as expected.
How can I get the behaviour I'm looking for?
This is what I managed to come up with after a bit of tinkering around. You can pass the click event from onclick into your handler function. If you let the event happen, it will just submit the form and prevent all following execution, that is why I stopped the original click event with preventDefault and triggered form.submit() programmatically.
Also notice how I wrapped the redirect inside a setTimeout to give time to the submit() to actually happen before the redirect.
<html>
<head>
<script type="text/javascript">
function testFunction(e) {
e.preventDefault();
e.target.parentNode.submit();
alert("Executing testFunction()!");
setTimeout(function() {
document.location.href = "http://www.google.com";
}, 0);
}
// uncomment this line to show that testFunction() does work when called directly
// testFunction();
</script>
<title>JS Redirect Then Post Test</title>
</head>
<body>
<form action="" method="POST" target="_blank">
First name: <input type="text" name="firstname"><br> Last name: <input type="text" name="lastname"><br><br>
<input type="submit" value="Submit" onclick="testFunction(event)">
</form>
</body>
</html>

How to load php file with JS code

Since I am new to JS coding and web designing, I have a following doubt:
I have one html page which has onclick function for form text area. If text area remains empty and user clicks submit, it should display message to enter entry and if entry is right one the corresponding file should get open. I have if/else condition in JS file, which is giving appropriate message while text area remains empty but not loading file which I am mentioning when entry is not empty.
Below is the html snippet:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset=utf-8>
</head>
<body>
<form name="drugform" action="#">
<pre> Drug Name<input type="text" name="name1" value="" /></pre>
</p>
<input type="button" value="Enter" onclick='buttoncheck()' />
</form>
<script type="text/javascript" src="if-else-button.js"></script>
</body>
</html>
and JS code is:
function buttoncheck() {
if (Boolean(document.drugform.name1.value)) {
load(form1.php);
} else {
alert('Enter Drug name');
}
}
How to load file with js code (mentioned in if condition)?
if you want to load that form1.php file in existing file then you can use ajax for for reference go here.
and if you want to redirect to another page then you should use
window.location.href = "form1.php";
var url = 'form1.php';
window.location.href = url;
Instead of load(form1.php), substitute the above code snippet!
EDIT:
If you want to load the file without actually redirecting to a new page, you can use jquery's .load()
Check more about it here: http://api.jquery.com/load/
try like this,
function buttoncheck() {
if (document.drugform.name1.value != "") { // check not empty condition
load("form1.php"); // passing value to function with quotes
} else {
alert('Enter Drug name');
}
}

Categories