Drupal Developer Tip: AJAX Views Updates

Submitted by Brandon Cone on 05/21/2013 - 10:06:am

We recently encountered a new task request from a client - update the results of a view without requiring the user to refresh the page.  Now, surely, making AJAX callbacks to retrieve new page content and modifying the contents of the page with jQuery are nothing new to the web development world.  However, what was new to us was appending the data to the view in a way that didn't result in multiple views (from the HTML perspective) rendered on the page.  

For static views, you can simply embed the view using views_embed_view(), but for this application that wouldn't work.  Our goal was to simply append the resulting rows to the view rather than add multiple rendered views to the page.

The solution we found turned out to be quite elegant, in our opinion. 

 

  1.   $view = views_get_view('my_view_name');
  2.  
  3.   // Set up the contextual filters for your view, if applicable
  4.   $args = array('my_view_arg_1', 'my_view_arg_2');
  5.   $view->set_arguments($args);
  6.  
  7.   $view->execute($display_id);
  8.   $view->preview();
  9.  
  10.   $results = array();
  11.   $renderer = $view->style_plugin->row_plugin;
  12.   foreach ($view->result as $index => $row) {
  13.     $view->row_index = $index;
  14.     $results[] = $renderer->render($row);
  15.   }

This will give you the rendered row results but will lack the views row classes.  You may, therefore, want to iterate these results and add your views-row and views-row-[row_number] classes to each row so that they will seamlessly integrate into your view.

Happy Coding!

 

Blog photo provided by Tahmid Munaz