Detect an AJAX Request with PHP

Sometimes you want to display a page of your site in a convenient popup using AJAX, the problem with this is in the popup your obviously not going to want your website header, footer, menu bar and etc and would need to return just the content for the popup.

Well with PHP this is easy, PHP can detect if the request is coming from a normal HTTP request or if it is coming from an AJAX request.

Some people might think "is this worth it?", "cant you just duplicate the content?" well yes it is worth it and no you should never duplicate content, Google has been able to parse JavaScript for a long time and can see your popups and will index your AJAX requests as pages, so duplicating the content is a very bad idea. Not only that it will mean you will have to modify 2 or more files every time you wish to update your content - which should never be an issue.

Using this method below you can detect if the request is coming from AJAX, and then do appropriate logic to ignore elements in the response you do not need to serve, this means you can provide a normal page URL as your AJAX request, so if a user goes directly to that page, or if google follows the link they will see the full site header, footer and etc. This is really good for usability, indexability and etc.

Using PHP to detect AJAX requests

All you need to do is use the following logic:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Request came through AJAX
} else {
//this is not an AJAX request...
}

 

Some servers however do not support this variable so if it does not work then you may need to find another solution, or configure your server to support this feature.

Facebooktwitterredditpinterestlinkedinmail
Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
, ,
0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments