How to Check for Ajax Requests With jQuery & PHP
Checking for AJAX requests from jQuery in PHP is important when you want to handle an AJAX request and a normal page load in different ways. For example, AJAX requests may send extra data that you need to process. AJAX are a series of methods that help provide dynamic Web content through asynchronous data transfers in the background of the page. Checking the state of the "HTTP_X_REQUESTED_WITH" variable lets you determine if the page load is from an AJAX request.
Instructions
-
-
1
Open your PHP file in a text editor, such as Notepad.
-
2
Check if the page is being called by an AJAX call. Paste the following code in the body of your PHP file:
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest')
{
// is an AJAX request so perform this code
}
The "strtolower" conversion is necessary to avoid any issues with the string comparisons. This works because AJAX queries from jQuery send the following header, which sets the "HTTP_X_REQUESTED_WITH" variable to have the value "xmlhttprequest":
xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
-
-
3
Handle non-AJAX requests by adding the following code:
else
{
// non-AJAX request code here
}
?>
-
4
Save the PHP file and load it on your server to check for AJAX requests.
-
1
Tips & Warnings
Remember to enclose all PHP code within "<?php" and "?>" tags.