Related concepts: HTML forms · AJAX POST · server-side email validation
Keep server-side validation authoritative even when JavaScript provides instant feedback. This example sends the email in the POST body, and the endpoint returns a plain-text validation message that the browser displays with textContent.
async function validateEmail(email) {
const body = new URLSearchParams({ email });
const response = await fetch('email-ajax.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body
});
document.getElementById('msg').textContent = await response.text();
}
<script type="text/javascript">
async function AjaxFunction(email) {
const body = new URLSearchParams({ email });
try {
const response = await fetch('email-ajax.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body
});
const message = await response.text();
document.getElementById('msg').textContent = message;
} catch (error) {
document.getElementById('msg').textContent = 'Unable to validate the email right now.';
}
}
</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
<?php
$email = trim((string)($_POST['email'] ?? ''));
$valid = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
echo $valid
? 'Valid email address.'
: 'Invalid email address.';
?>
The same server-side validation can use PHP's built-in email filter function.
if(filter_var($_POST['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.