Skip to main content

Drupal 8: Rendering views through Ajax

Drupal 8 includes views in the core. Views (module) is one of the most powerful functionality of Drupal. This is a views/ajax api snippet to call the views with some arguments and views details.

let contentWrapper = '#div-id';
let args = [arg1,arg2];
 'url': Drupal.url('views/ajax'),
 'type': 'POST',
 'data': {
   'view_name': 'view_name',
   'view_display_id': 'block|page',
   'view_args': args,
 'dataType': 'json',
 'async': false,
 'success': function (response)  {
   if (response[3] !== undefined) {
     var viewHtml = response[3].data;
     // Remove previous div html inner data and add the new ones.
     // In order to keep the Ajax functionality of the view this is the crucial part
     // Attach Latest update to settings to the behaviours and settings. 
     Drupal.settings = response[0].settings;
     drupalSettings.views = response[0].settings.views;
     Drupal.attachBehaviors($(contentWrapper)[0], Drupal.settings);