Skip to main content
hook ajax in views

Drupal 7 - Hooking Ajax events and views refresh

Drupal has a solid Ajax interface, we can hook into the Ajax events at various places. I will explain some 5 important methods,
 
1) beforeSerialize - called before data is packed and runs before the beforeSend & beforeSubmit
2) beforeSubmit - called before the ajax request
3) beforeSend - called just before the ajax request
4) success - called after ajax event returns data
5) complete - called after the request ends
 
Lets say you want to capture some ajax event (in built or made by other module) to do some event like Views refresh. We can use a very simple logic to do that.
 
(function($) {
    Drupal.behaviors.timetracker = {
        attach: function(context, settings) {
        /*Task submit ajax*/
        for (ajax_el in settings.ajax) {    
          if (Drupal.ajax[ajax_el].element.form) {
             if (Drupal.ajax[ajax_el].element.form.id === 'TYPE-node-form') {
               //called before the ajax request
               Drupal.ajax[ajax_el].beforeSubmit = function(form_values, element_settings, options) {
               //Do something                      
               }

               Drupal.ajax[ajax_el].beforeSend = function (xmlhttprequest, options) {

                //Do something                      
              }

              //called before data is packed
              Drupal.ajax[ajax_el].beforeSerialize = function(element_settings, options) {
               //Do something     
              }              

             //Called after ajax event returns data
              Drupal.ajax[ajax_el].success = function(response, status) {
                 // Trigger views refresh refresh the activity view
                 $('.view-id-activity').trigger('RefreshView');
                 //Pass back to original method
                 Drupal.ajax.prototype.success.call(this, response, status);
             }

             Drupal.ajax[ajax_el].complete = function(response, status) {
            }
       }
      }
    }
  }
}
});

In my case, I get all the forms that are set for Ajax handling and compare them with my node form. Once the form submission happens and the ajax data is returned, "success" method will get called. As the new data is added, I here refresh the respective view with the inbuilt Drupal procedure to refresh View.  Note, I use  Drupal.ajax.prototype.success.call to make sure the core function runs at the end, otherwise you may notice inconsistency.

I hope this sheds some light, let me know if you need some inputs from me.

 

Comments

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.