Skip to content

AJAX Requests with PHP

Recently I’ve seen a lot of questions on stackoverflow about how to detect/respond to AJAX requests. It’s actually quite simple. Most of the major players in the javascript framework will send a specific header(X-REQUESTED-WITH) to the requested page. You can check this header to detect AJAX requests.

if (
    isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
    strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest'
) {
    // AJAX request
}
else {
    // Normal request
}

You can add this to your request object or define a constant

define(
    'IS_AJAX_REQUEST',
    (bool)isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest';
);

Example usage

// Get an array of contacts for a user
$contacts = Contacts::getForUser( $user_id );
 
// If the page was requested via ajax, json encode the array and exit the script
if ( IS_AJAX_REQUEST ) {
    die( json_encode( $contacts ) );
}
 
// Normal request, require the view
require( 'views/contacts.php' );

Frameworks verified to use the X-REQUESTED_WITH header

Prototype, Jquery, Dojo, Mootools, YUI

Categories: Javascript, PHP.

Tags: , , , , ,

Comment Feed

No Responses (yet)



Some HTML is OK

or, reply to this post via trackback.