What is the best way to load async data in Drupal 7?
Curriently I’m loading my data with jQuery with my own nodes. I have build an own menu_hook which is aviable under /events and e.g. /events/2012-04-17 this page is also aviable for normal browsing. I check if $_SERVER['HTTP_X_REQUESTED_WITH'] is set if it is I return the data in a JSON string and parse the data.
Can I run in some trouble if I activate some caching technics? Or is there a better way to load the data? It seems that this does not work with boost because I’m killing the script with die() what could I do else?
function my_module_menu() {
$items['events'] = array(
'page callback' => 'event_page',
'access callback' => TRUE,
'type' => MENU_LOCAL_TASK,
);
$items['events/%date'] = array(
'page callback' => 'event_page',
'page arguments' => array(2),
'access callback' => TRUE,
'type' => MENU_VISIBLE_IN_BREADCRUMB,
);
return $items;
}
function event_page($date=null) {
$build=array();
// add some other "controls"
$build['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
if((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'XMLHttpRequest' == $_SERVER['HTTP_X_REQUESTED_WITH']) || strpos($_SERVER['REQUEST_URI'], '?json')!==FALSE) {
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json', true);
$json=loadData();
die(json_encode($json));
}
return $build;
}
You can use drupal_json_output instead, this will automatically change the headers so no exit() is required.
Another option would be to change the delivery callback on that particular path combined with the data from $_SERVER using hook_page_delivery_callback and then return a valid array for the page using ajax_command‘s.
The first option is alot easier, I’ve never tried the second one myself but it might be too much for your situation. Unfortunately I don’t know how either of these techniques behaves together with boost but hopefully one of them will work.