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.

If you’re using Zend_Controller_Front, you can call the the isXmlHttpRequest() method on the request object.

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.

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.

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *