blog-banner

Drupal 7 - Hooking Ajax Events and Views Refresh

  • Ajax
  • Drupal
  • Drupal Planet
  • Views

Drupal 7  Ajax

 
Drupal has a solid Ajax interface, we can hook into the Ajax events at various places. I will explain 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
 
Let's say you want to capture some ajax event (inbuilt or made by other modules) to do some event as Views refresh. We can use 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, the "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 the inconsistency.

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

 
Get awesome tech content in your inbox