Monday, June 14, 2010

3:54 AM
3

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.

 

3 comments:

Unknown said...

Hi, nice blog for learning PHP. I came here from a link you put on nerds-central, so I am sure you'll be cool about a back link :)

For powerful solutions to COBOL, VB, Java and much more - visit http://nerds-central.blogspot.com

Unknown said...

For more tutorials on jQuery, PHP, CSS, visit www.webspeaks.in

valentinas said...

Interesting. But why don't you simple use a GET variable, for example ajax=1?

Then you could simply do

if($_GET['ajax']==1){
//do stuff here
}

Your way of doing it is interesting, but I don't think it's better. I would like to know why do you use this kind of check instead of passing simple variable via GET or POST.