Spiff Up Your Drupal AJAX Interactions

This is a synopsis of http://kevinquillen.com/javascript/2014/06/04/kill-the-ajax-throbber/ This javascript example shows how to react when ajax events are first triggered, how to react when the ajax event completes, and how to use "settings.extraData" to pass values from the send event to the complete event. It also demonstrates how to get the triggering elements name using settings.extraData._triggering_element_name. The JS below is a simple example which would affect every ajax event, most likely not what you want.

(function($, Drupal, window, document, undefined) {
  Drupal.behaviors.ajaxspiffyexample = {
    attach: function() {
 
      $(document)
        // Reacts when AJAX events are sent.
        .ajaxSend(function(e, xhr, settings) {
          // Stores the name of the triggering element.
          var trigger = settings.extraData._triggering_element_name;
          // Gets the id of the parent table row.
          var parent = $('input[name="' + trigger + '"]').closest('tr').attr('id');
          // Fades the parent.
          $('#' + parent + ' td.subtotal').fadeTo('150', '.5');
          // Saves the id of the parent in settings.extraData so that it's available
          // in ajaxComplete().
          settings.extraData.parentElement = parent;
        })
        // Reacts when AJAX events are completed.
        .ajaxComplete(function(e, xhr, settings) {
          // Gets the parent element by id from settings.extraData, which was saved
          // above in ajaxSend().
          $('#' + settings.extraData.parentElement + ' td.subtotal')
            // Fades the parent back in.
            .fadeTo('150', '1');
        });
 
    }
  };
})(jQuery, Drupal, this, this.document);

Internal References

External References

Article Type

General