Created
February 9, 2015 11:27
-
-
Save alcroito/8f75c7d42acfd6566f2f to your computer and use it in GitHub Desktop.
Drupal Ajax Response caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implements hook_menu(). | |
*/ | |
function custom_module_menu() { | |
$items = array(); | |
$items['custom-module-ajax'] = array( | |
'page callback' => 'custom_module_data_ajax', | |
'access arguments' => array('access content'), | |
'type' => MENU_CALLBACK, | |
); | |
return $items; | |
} | |
/** | |
* Ajax callback that returns a JSON object. | |
*/ | |
function custom_module_data_ajax() { | |
// Assign the data here. | |
$response = array('a', 'b', 'c'); | |
$response_json = drupal_json_encode($response); | |
// Print the response + the content type header. | |
drupal_add_http_header('Content-Type', 'application/json'); | |
print $response_json; | |
// Disable page compression for AJAX requests, because it breaks caching. | |
// Browsers don't seem to be able to decompress the return GZIPed json data. | |
global $conf; | |
$conf['page_compression'] = FALSE; | |
// Call this to cache the result of the ajax callback for anonymous users. | |
drupal_page_footer(); | |
// Need to call exit as well, otherwise the html delivery callback will also | |
// be executed, and it will try to send headers after the content was sent. | |
exit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out this one: https://gist.github.com/rogercodina/b1687e078597f60044ff234e84e2f22f