Keep server-side validation authoritative even when JavaScript provides instant feedback. A small endpoint can return JSON that the browser uses to update the form.
header('Content-Type: application/json; charset=UTF-8');
$email = trim($_POST['email'] ?? '');
$valid = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
echo json_encode(['valid' => $valid]);
This is the recommended starting pattern. The detailed examples below are retained for explanation, comparison and related variations.
<script type="text/javascript">
function AjaxFunction(email)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
document.getElementById("msg").innerHTML=httpxml.responseText;
}
}
var url="email-ajax.php";
url=url+"?email="+email;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
The HTML code to display the form ( as in the above demo ) is here
<form name=f1 action=''>
Your First Name <input type=text name=n1><br>
Any email address <input type=text name=email onBlur="AjaxFunction(this.value);">
<div id="msg"></div>
<br>
Your City Name <input type=text name=city>
<input type=submit value=Submit >
<input type=hidden value=test name=todo>
</form>
Now the code kept within email-ajax.php file is here, this is same code as explained at email validation tutorial
<?
$email=$_GET['email'];
echo $email;
if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $email)){
echo "<font color=red> Invalid email</font>";
}else{
echo "<font color=green> Valid Email</font>";}
?>
The above code in email-ajax.php file can be replaced by this code if you are using email filter function .
if(filter_var($_GET['email'],FILTER_VALIDATE_EMAIL)){
echo " Correct email "; }
else{ echo " Wrong email address "; }
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.