Easy Ajax

I found this link mrkadin.com/blog/node/70 on Planet Drupal, and thought it was a helpful start to setting up Ajax the easy/lazy way using views.  I extended it to a bit more generic as follows:

1. Make the ajax callback url used in the rewrite in the view 'common-ajax/nojs/{VIEWNAME}/{VIEW ARGUMENT}'

2. Create a module with the following code to handle the callback:

function common_menu() {
        $items['common-ajax/%/%'] = array(
                'access arguments' => array('access content'),
                'page callback' => 'common_ajax_callback',
                'page arguments' => array(1,2),
                'type' => MENU_CALLBACK,
        return $items;

function common_ajax_callback($js, $view_name, $param1) {
  $view = views_get_view($view_name);
  $view->set_display('default');  // Currently, only the 'default' display id is used here
  // If the nojs didn't get changed to ajax, the user has no javascript.
  // Display as a normal (non-ajax) page
  if ($js == 'nojs') {
      $view->use_ajax = FALSE;
      $view->is_attachment = TRUE;
  //print the rendered version of your view
  $html = $view->render();
  // Prepare an ajax command to insert the node html into our ajax wrapper.
  $commands = array();
  $commands[] = ajax_command_html('#common-ajax-wrapper', $html);

  // Render the commands into JSON and print them.
  print ajax_render($commands);
  exit;  // Exit so Drupal doesn't have a chance to build a whole page.

3. Add a div with id common-ajax-wrapper to page.tpl.php for the theme


This creates a nice generic version which allows any view to be used, with one parameter (although this could be easily extended to cater for any number of parameters)


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.