Skip to main content

Drupal Refresh View on AJAX Event

DrupalVIP Support

This javascript runs on views with AJAX enabled, evaluates the Drupal.views.instances object to look for a view name, if the view name is found, jQuery's ajaxComplete method is attached to the document. 

When an AJAX call completes, the ajaxComplete method evaluates the returned response and looks for a specific callback name, in this case editablefields_form_update, and updates the view by issuing a click on the hidden view refresh link that the function also adds.

Developer note: 
Drupal's response JSON does not provide a pretty set of Object keys to use to access different areas of the response, but JavaScript has a nifty trick for finding out a name of an object key: Object.keys(object-to-be-evaluated). 
You'll notice this is in use in the gist above to access the response settings callback, which, in Drupal's response JSON, is in an object below an object named after the id of the object that issued the request.

 

jQuery(document).ready(function(){
  jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
})

/**
 * Function built on wireframe from 
 * https://drupal.org/node/1781988#comment-6835168
 */
Drupal.behaviors.my_view_machine_name = {
  attach: function(context, settings) {
    if (Drupal.views !== undefined) {
      jQuery.each(Drupal.views.instances, function(i, view) {
        if (view.settings.view_name == "my_view_machine_name") {
          jQuery(document).ajaxComplete(function(event, xhr, settings){
            jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
            var response = JSON.parse(xhr.response);
            var resp_keys = Object.keys(response[0].settings.ajax);
            if (response[0].settings.ajax[resp_keys[0]].callback == "editablefields_form_update") {
              jQuery('#view-auto-refresh').click();
            }
          });
          view.$view.once('view-refresher', function() {
            var html = 'Refresh';
            view.$view.append(jQuery(html).each(jQuery.proxy(view.attachPagerLinkAjax, view)));
          });
          return false;
        }
      });

    }
  }
}