2

I feel like I'm doing something really wrong here. I have a View block which has an exposed filter. Since it is in a block I have to use Ajax. I'm trying to run some JS on the views result but can't get anything to happen when the ajax call completes.

To try and keep this as simple as possible I have created a test.js file with only the following code:

(function ($) {
  $(document).ajaxComplete(function (e, xhr, settings) {
    console.log('test');
  });
})(jQuery);

I add this with my theme's template.php file but when I filter my view and the results update with ajax, this code does not seem to run. I can't work out why not.

EDIT: I managed to get this to work by moving the code inside my_view.tpl.php but I'd be keen to know why it doesn't work in an external file.

3

JS events need to be bound when the document is ready. Drupal handles this for you if you use behaviors:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $(document).once('mymodule-ajax').ajaxComplete(function (e, xhr, settings) {
      // ...
      });  
    }
  }
})(jQuery);
1

I was trying to execute javascript after Ajax Views load content. Using Drupal 8.5 and Better Exposed Filter contrib module I did :

(function($, Drupal, drupalSettings) {

  Drupal.behaviors.myModuleScript = {

    attach: function(context, settings) {
      // Attach action to Drupal Ajax Views event
      $(document).once('weberAjaxViews').ajaxSuccess(function (event, data) {
        if (drupalSettings && drupalSettings.views && drupalSettings.views.ajaxViews) {

          var ajaxViews = drupalSettings.views.ajaxViews;
          Object.keys(ajaxViews || {}).forEach(function (i) {
            if (ajaxViews[i]['view_name'] == 'your_view_name' &&  ajaxViews[i]['view_display_id'] == 'your_view_display_name') {
              // Do some JS here
            }
          });

        }
      });
    }

  };

})(jQuery, Drupal, drupalSettings);

I have been using ajaxSuccess instead of ajaxComplete so my code does not get executed when the Ajax call throws an Error.

  • Thanks, this has been really helpful. I was able to add a class on "AjaxStart" and then remove the class on "AjaxSuccess". – Stef Van Looveren May 23 at 8:12
0

Have a look at my answer on another question that uses the betterExposedFilter module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.