Skip to content

Instantly share code, notes, and snippets.

@mordonez
Last active December 18, 2015 02:49
Show Gist options
  • Save mordonez/5713883 to your computer and use it in GitHub Desktop.
Save mordonez/5713883 to your computer and use it in GitHub Desktop.
Drupal: Do some staff when a node is viewed (AJAX version)
(function($) {
// updates the ...
$.ajax({
url: "/my_module/update/" + Drupal.settings.my_module_node.nid,
type: "POST",
dataTypeString: "text"
});
})(jQuery);
<?php
/**
* Implements hook_node_view().
*/
function my_module_menu() {
$items = array();
$items['my_module/update/%node'] = array(
'title' => 'my_module_ajax update',
'page callback' => 'my_module_ajax_update',
'page arguments' => array(2),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_node_view().
*/
function my_module_node_view($node, $view_mode, $langcode) {
if (!empty($node->nid) && $node->type === 'MY_CONTENT_TYPE' && in_array($view_mode, array('full'))) {
$node->content['#attached']['js'] = array(
drupal_get_path('module', 'my_module') . '/my_module.js' => array(
'scope' => 'footer'
),
);
$node->content['#attached']['js'][] = array(
'data' => array(
'my_module_node' => array(
'nid' => $node->nid
)
),
'type' => 'setting',
);
}
}
/**
* @param node object
* @return JSON indicating success or failure
*/
function my_module_ajax_update($node) {
// Only accept POST calls
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
drupal_json_output(array(
'status' => t('error'),
'data' => t('unknown HTTP method'),
));
exit;
}
if (!$node) {
drupal_json_output(array(
'status' => t('error'),
'data' => t('node does not exist'),
));
exit;
}
// YOUR CODE HERE...
drupal_json_output(
array(
'status' => t('success'),
'data' => t('node tracked'),
)
);
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment