Detect an AJAX Request in PHP

I like using the same PHP script for both AJAX and non-AJAX content requests. Using one script just makes everything easier because it's only one file to update/edit and it's one more cache-able request. One way to try detect an AJAX request (as opposed to a regular page load) is by using the following PHP code:
/* decide what the content should be up here .... */
$content = get_content(); //generic function;

/* AJAX check  */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 /* special ajax here */
 die($content);
}

/* not ajax, do more.... */
$_SERVER['HTTP_X_REQUESTED_WITH'] is the golden ticket but not all servers provide this variable so having other checks in place will be important.

Comments

Popular posts from this blog

Installing SSL Certificate from CPanel

How To Save Streaming Videos And Songs Without Any Downloader