Guides
Last updated
December 28, 2023

How To Validate Email Addresses with AJAX and PHP

Shyam Purkayastha

Table of Contents:

Get your free
Email Validation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

AJAX stands for Asynchronous JavaScript and XML. It is one of the critical technologies that have spearheaded the advancements in web applications in the form of dynamic web content. This post will explore how AJAX and PHP can be leveraged for email address validation within a web application.

What is AJAX?

The term AJAX was coined during the early 2000s to represent a set of prevalent technologies capable of creating a more seamless interaction between users and web pages. The three terminologies in this acronym are Asynchronous, JavaScript, and XML.

The term asynchronous, or async, in AJAX, stands for a technique that enables behind-the-scenes updates on a web page without reloading the entire page, which was the common practice in web applications of the Web 1.0 era. JavaScript is the popular client-side scripting language used in web development to build dynamic, interactive web pages. XML is a data format used to exchange data between two endpoints over the Internet.

These three technologies form the bedrock for a dynamic, interactive, and user-friendly web application. In recent times, the concept of AJAX has undergone improvements, such as the introduction of new data formats like JSON. New protocols, like WebSockets, have also been introduced, which can work in conjunction with HTTP, the de-facto protocol AJAX uses. WebSocket offers bi-directional communication between a client web page and the web server. In contrast, HTTP and AJAX work on a request response-based interaction, where the request is always initiated from one direction, the client.

Using AJAX & PHP for Email Validation

Email addresses are one of the most important information in web applications. They are used not only for communicating with the users but also as a unique identifier for users. Therefore, an email address is always part of most web forms, such as a contact form, presented by a web page.

Without using AJAX, any web form submitted by a user causes the entire web page to refresh to display the form submission result. Using AJAX, the form data can be sent asynchronously, and only a small portion of the web page is updated to display the submission status without causing the reload of the entire web page.

Let’s build a sample web application to understand the concept of AJAX and demonstrate how to use it for email address validation.

Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

Development Environment for AJAX PHP Email Validation

This sample application uses a simple web page consisting of a form containing the email address field and a submit button.

Prerequisites

To replicate this application, you must have a working installation of the PHP runtime on your computer with version 8 or above. Check the official PHP download page for the PHP installation packages as per your operating system.  

It would also help to have a top-level project directory to contain the source files for this sample application.

Frontend form for email submission with AJAX

The frontend web page for this sample application contains the web form, containing a single, default input type field, for submitting the email address. Here is the complete source code for the HTML web page.












AJAX Email Validation Demo
























































Let’s understand the intricacies of this web page to understand how AJAX is implemented here.

This HTML file is a Bootstrap-based web page containing a form element with an <input> element. There is a submit button that has a click event associated with it. There is also an empty <div> element, with the id as “result”,  above the form element for displaying the form submission result.

The AJAX functionality is implemented inside the click event. We have used the popular JQuery $.ajax( ) function. This function makes an HTTP POST request to the server and submits the form data. The HTTP response is handled in the anonymous function assigned to the success parameter of the $.ajax call. It updates the <div> element with the success message returned by the server. This function is always invoked when the server returns a 200 response, which indicates a successful HTTP response.

Save this file as index.html under the project directory.

Backend PHP Script for handling Email validation

Here is the backend PHP script for handling the server-side logic of email validation.




$email = $_POST['email'];


http_response_code(200);


// Perform email address validation using filter_var()

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo 'Email address is valid.';

} else {

echo 'Invalid email address.';

}

?>

This PHP script is a simple implementation of the server-side response for AJAX calls. It performs a format validation on the email address using the filter_args( ) function. Based on the validation result, it returns a response, which is displayed on the web page.

Save this file as index.php under the project directory.

Testing the Email Validation Logic

To test this application, follow the steps below:

  1. Open a terminal window and change the directory to your project’s top-level directory.
  2. Launch the PHP development server by running the following command.

php -S localhost:8000


  1. Launch a browser tab and open the URL http://localhost:8000/index.html
  1. Test the form by submitting an invalid and valid email address.


The JQuery AJAX is at play here. Whenever you submit the email address through the input field, an AJAX interaction happens between the client web page and the server PHP script to serialize the email address and check its format validity to return the validation status.

This way, you can use JavaScript to make asynchronous HTTP calls to the server and dynamically update any HTML div element without reloading the entire web page. And that’s precisely AJAX. The only difference here is the use of JSON as a data format instead of XML since JSON has gained preference over the years and has replaced XML. Therefore, some publications on web development now refer to AJAX as AJAJ.

Error Handling in AJAX

The AJAX code presented in the previous section is a bare-bones implementation. Unfortunately, many things can go wrong in a real-world AJAX  application, which needs to be handled.

For every AJAX call, two primary errors must be handled:

  1. HTTP 4xx and 5xx errors: HTTP response codes returned from the server. These codes must be programmed in the PHP script to ensure the server returns an appropriate code to the client web page in case of specific error situations. It ensures consistent error handling and user experience.
  1. Network timeout: Since AJAX works over the Internet, any disconnection or delays in HTTP interaction between the client and server must be handled gracefully to inform the user about the issues.

Here are the modified versions of index.html and index.php with error handling.












AJAX Email Validation Demo































































$email = $_POST['email'];


// Perform email address validation using filter_var()

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

// Valid email address

http_response_code(200);

echo json_encode(['message' => "Email address is valid."]);

} else {

// Invalid email address

http_response_code(400);

echo json_encode(['message' => "Invalid email address."]);

}


?>

You can see two modifications in the $.ajax( ) call. One is the error parameter which is assigned a function to handle errors. This function gets called when the server returns an HTTP response of 400 or 500. The second modification is styling the <div> element to change the text color for success and error messages. The $.ajax( ) call also adds a timeout of ten seconds and handles the timeout error to display an appropriate message.

In the PHP script, HTTP return codes have been added to handle 200, a success response for valid email address validation, and a 400 failure response for invalid email address validation.

You can replace the existing index.html and index.php files with these versions to do a quick test by performing a form submit for an invalid and valid email address.

As you can see, the client-side AJAX calls can now differentiate between success and failure responses and update a color-coded text message on the web page.

To test the timeout scenario, you can modify the index.php AJAX handling code to add a sleep function before the if block to simulate a server delay.


sleep(12000);

This will lead to a twelve-minute delay in server response, by which time the $.ajax call will return with the timeout error since we have set the timeout parameter to ten minutes. Upon timeout, the webpage will be updated with a message indicating the same.

A More Reliable Email Validation using AbstractAPI

The email address validation technique used until now relies on a native PHP approach to check the address format. This approach has a severe limitation in that it cannot assert the deliverability of the email address. If you plan to use the email address submitted by the user for future correspondence, it is essential to validate the deliverability of the email address.

Fortunately, there is an easy way out. Using the Abstract Email Validation and Verification API, you can get a detailed report on the legitimacy of any email address, including its deliverability.

Here is another modified version of index.php that uses the Abstract API endpoint.





function validation_with_abstract($email)

{

$url = "https://emailvalidation.abstractapi.com/v1/?api_key=" . "" . "&email=" . $email;

$curl = curl_init();

curl_setopt_array($curl, array(

CURLOPT_URL => $url,

CURLOPT_RETURNTRANSFER => true,

CURLOPT_ENCODING => '',

CURLOPT_MAXREDIRS => 10,

CURLOPT_TIMEOUT => 0,

CURLOPT_FOLLOWLOCATION => true,

CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

CURLOPT_CUSTOMREQUEST => 'GET',

CURLOPT_HTTPHEADER => array(

'Content-Type: application/json',

'Accept: application/json'

),

));

$response = curl_exec($curl);

curl_close($curl);

$response = json_decode($response, true);




if (($response['deliverability'] !== 'DELIVERABLE')) {

return false;

} else {

return true;

}

}


$email = $_POST['email'];


// Perform email address validation using filter_var()

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {



// Valid email address

if(validation_with_abstract($email)){

http_response_code(200);

echo json_encode(['message' => "Email address is valid."]);

} else {

http_response_code(406);

echo json_encode(['message' => "Email address valid but not deliverable."]);

}



} else {

// Invalid email address

http_response_code(400);

echo json_encode(['message' => "Invalid email address."]);

}


?>

This script uses the PHP cURL library to make an API call to the Abstract Email Validation and Verification API. You can sign up for a free Abstract account and get access to your API key under the dashboard.   After replacing the existing index.php with this code, replace the placeholder <YOUR_ABSTRACT_APIKEY> with the API key allotted to you, before saving the file.

You can also notice that the PHP script now performs email validation at two levels. At the first level, it does a basic format check and returns a 400 response in case of an invalid format. At the second level, the Abstract API is invoked to return a 200 or 406 error corresponding to the deliverability status. This way, you can return a more granular set of error codes in the AJAX call based on the server’s implementation.

Now, the AJAX call will be able to differentiate between a valid email address that is deliverable from the one that is not. Here is the accompanying modified index.html for handling 200 and 406 HTTP response codes. An additional orange color is added to display the email address validation status, which is not deliverable.












AJAX Email Validation Demo
























































A quick test with valid and invalid email addresses displays all three results for:

  • An invalid email address.
  • A valid email address.
  • A valid email address that is not deliverable.  

With this, your AJAX implementation is complete, and you can perform email address validation considering all the common failure scenarios. You can replicate this code to implement a more complex form submission with additional data.

Note: In this tutorial, specific HTTP response codes like 406 have been used based on the application logic’s discretion. This is done to explain how to handle success and failure scenarios in AJAX calls. In a real-world scenario, many such response codes have specific, pre-defined meanings and should not be used to handle application-level errors. In such cases, a 200 success response code with additional data fields must be used to indicate errors.

FAQ

How can I validate an email address using AJAX and PHP?

Validating an email address using AJAX (Asynchronous JavaScript and XML) and PHP involves creating a communication flow between the front end (using JavaScript and AJAX) and the back end (using PHP for server-side processing). For the front end, you can use the popular JQuery library, which offers the $.ajax( ) function to perform AJAX calls. This call triggers an HTTP request with the payload containing the email address. You can implement a basic email validation check at the back end using the PHP filter_var( ) function. You can also leverage the Abstract Email Validation and Verification API for more advanced validation.

How to debug common issues in AJAX PHP email validation?

Most of the issues in AJAX calls are due to network timeouts or HTTP errors. To debug the problems in AJAX, you must handle the error block in the JQuery $.ajax( ) call, which contains a lot of information about the HTTP response codes and error strings. Most importantly, you must handle timeout and HTTP response codes in the 4xx and 5xx categories. Timeout can happen due to network delay and server unavailability. 4xx codes indicate a client-side error, and 5xx codes indicate a server-side error. For conveying application-related errors, you can use the 4xx error codes or a 200 success response with the additional field in the JSON response payload containing error information.

What are the prerequisites for implementing email validation with AJAX and PHP?

To implement AJAX, you need a JavaScript API to perform AJAX calls from the webpage. You can use native browser API like the fetch( ) function. To avoid browser-to-browser inconsistencies, it is best to use a common library like JQuery, which offers a set of AJAX methods like $.ajax( ),  $.post( ), and $.get( ) to perform AJAX calls in a browser-agnostic way. If your web application is built using a framework such as Angular or React, you get specific APIs available in those frameworks for performing AJAx calls. If you are using vanilla PHP on the server side, you can use the built-in PHP super global variables like $_SERVER,  $_POST, and $_GET to check for AJAX requests coming from the client, extract and process the AJAX payload, and return an appropriate response with an HTTP response code. In the case of using a PHP framework like Laravel or CakePHP, you have access to the framework-specific directives for handling AJAX calls instead of reading the raw data directly from the super global variables.

Shyam Purkayastha

Shyam Purkayastha is a proficient web developer and PHP maestro, renowned for his expertise in API creation and integration. His deep knowledge of PHP scripting and backend development enables him to build scalable server-side applications. Shyam is particularly passionate about RESTful API design, significantly enhancing web service functionality and data interoperability.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required