Drupal 8 Render views through Ajax

leopathu on Fri, 07/24/2020 - 14:58
drupal-views

Views is one the powerful functionality of the Drupal, Drupal 8 includes it in the core. We mostly used to export and present the data as a page, block and REST api, but there is one more way to render the views from jquery with the help of ajax. There is views/ajax api path to call the views with some arguments and views details(name, display id etc..).

The below code show you to render a views through ajax,

$.ajax({
 'url': Drupal.url('views/ajax'),
 'type': 'POST',
 'data': {
   'view_name': 'your_view_name',
   'view_display_id': 'block',
   'view_args': viewArgs,
  },
 'dataType': 'json',
 'async': false,
 'success': function (response)  {
   if (response[3] !== undefined) {
     var viewHtml = response[3].data;
     // Remove previous articles and add the new ones.

     $(contentWrapper).html('');
     $(contentWrapper).append(viewHtml);
    
     // Attach Latest settings to the behaviours and settings. 
     // it will prevent the ajax pager issue
     Drupal.settings = response[0].settings;
     drupalSettings.views = response[0].settings.views;
     Drupal.attachBehaviors($(contentWrapper)[0], Drupal.settings);
   }
   }
 }
});

In that code we just do the POST ajax request to the views/ajax path with the data view_name, view_display_id, view_args (if you have any contextual filter)

Views_args should be in a string in the following format if you have multiple contextual filter values,

firstArg/secondArg/thirdArg

If you want to send multiple arguments value to the secondArg use the below method

For AND Operation: firstArg/secondArg1+secondArg2/thirdArg

For OR Operation: firstArg/secondArg1,secondArg2/thirdArg

Finally ajax response will have the html data in the response[3].data. Just we have to place the content to our html wrapper where the data to be presented.

Important thing in that, We have rebuild the attachBehaviours and Drupal.settings with the views latest response settings, Then only the views functionality works fully. Other wise the pager and ajax functionality won’t work in the rendered views.

I hope, you have learned something interested in this blog about the views.

 

Tags

Add new comment