Skip to content

Instantly share code, notes, and snippets.

@alcroito
Created February 9, 2015 11:27
Show Gist options
  • Save alcroito/8f75c7d42acfd6566f2f to your computer and use it in GitHub Desktop.
Save alcroito/8f75c7d42acfd6566f2f to your computer and use it in GitHub Desktop.
Drupal Ajax Response caching
/**
* 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();
}
@rogercodina
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment