Last active
December 18, 2015 02:49
-
-
Save mordonez/5713883 to your computer and use it in GitHub Desktop.
Drupal: Do some staff when a node is viewed (AJAX version)
This file contains hidden or 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
(function($) { | |
// updates the ... | |
$.ajax({ | |
url: "/my_module/update/" + Drupal.settings.my_module_node.nid, | |
type: "POST", | |
dataTypeString: "text" | |
}); | |
})(jQuery); |
This file contains hidden or 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
<?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