AJAX Requests and 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.
1 2 3 4 5 6 7 8 9 | 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
1 2 3 4 | define( 'IS_AJAX_REQUEST', (bool)isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest'; ); |
Example usage
1 2 3 4 5 6 7 8 9 10 | // 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
