I find this code in W3Schools. It's about form validation with Javascript.
When the user tape wrong mail format, an alert is appear.
When I check the code I see on form onsubmit="return validateForm();
, well the function return false in error case.
So my question is how to get the boolean value from javascript to use it in PHP to write error message instead of use of message box.
This is my code:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["email"].value
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
Thanks in advance.
Ali
You can't get the boolean value from javascript. What you need to do is have an error div ready in advance. Something like this:
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<div id="error"></div>
<input type="submit" value="Submit">
</form>
Add css to it to hide it. Then in your validation form, use javascript to alter the HTML of the error div.
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
document.getElementById("error").innerHTML="Not a valid e-mail address";
return false;
}
The "return false;" part is to tell the form not to submit. As mentioned in other answers PHP and Javascript do not interface. PHP is server side, Javascript is client side. They don't talk to each other. They can, however, both modify the HTML. Just remember, Javascript always runs in the browser. So if it needs to send things to PHP you need to use AJAX to call a server side PHP script and send the information that way. Most of the time, however, when you are using Javascript, it isn't PHP that needs the information, it's the user. So using Javascript to modify the HTML does the trick.
if (..)
{
document.getElementByID('error').InnerHTML = "Not a valid e-mail address!";
return false;
}
else
{
document.getElementByID('error').InnerHTML = "";
}
and in your markup add:
<span id="error"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With