Detecting Ajax Requests With PHP
In this PhpRiot Snippet I will show you how can detect if a HTTP request was an Ajax request. Ajax requests are performed in JavaScript using the XMLHttpRequest component.When such a request is made, a HTTP header called
X-Requested-With
is sent. The corresponding value for this header is XMLHttpRequest
. You can access these headers from the PHP superglobal $_SERVER
.
PHP renames HTTP request headers so dashes become underscores and all letters are made upper-case. Therefore we can check
$_SERVER['X_REQUESTED_WITH']
.
Therefore you can use the following code to check if a request is from an Ajax request.
Listing 1 Checking if a request is an Ajax request (listing-1.php)
$isXmlHttpRequest = array_key_exists('X_REQUESTED_WITH', $_SERVER) && $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest'; if ($isXmlHttpRequest) { // is an Ajax request } else { // is not an Ajax request }
If you're using
Being able to check if a request is useful to determine what kind of
content to send back. For example, if the request is an Ajax request
you may want to send back some JSON data, whereas if it's not you may
just want to return normal HTML.
Zend_Controller_Front
, you can call the the isXmlHttpRequest()
method on the request object.
In the following listing I demonstrate this. If the request is an Ajax request we sent some JSON data back, otherwise we fall through and output normal HTML.
Listing 2 Outputting JSON data for Ajax requests only (listing-2.php)
$isXmlHttpRequest = array_key_exists('X_REQUESTED_WITH', $_SERVER) && $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest'; if ($isXmlHttpRequest) { $data = array( 'foo' => 'bar' ); header('Content-type: application/json'); echo json_encode($data); exit; } <html> <head><title>Normal page content</title></head> <body> <!-- normal page content --> </body> </html>
Other Options
- Download a PDF version of this article
- Put your PHP knowledge to the test with our online and iPad/iPhone quizzes
- View or post comments for this article
- Browse similar articles by tag: Ajax, PHP
No comments:
Post a Comment