12

I have a form that has an AJAX button. When I click it, it updates a bunch of stuff as expected which is fine.

I was wondering if there is a way to create a listener in behavior that gets called when the AJAX call is complete?

Thanks

21

Yes, there is :

Drupal.behaviors.YourBehaviour = {
attach: function(context, settings) {  
  $('#yourform').ajaxComplete(function(event, xhr, settings) {
    if ($(event.target.id) == 'the-id-of-your-item') {
      // Your code here
    }
  });
 }
}
| improve this answer | |
  • 2
    +1, but for Drupal 7 it would be Drupal.behaviors.YourBehaviour = { attach: function() { $('#yourform').ajaxComplete... – Clive Jun 1 '12 at 14:10
  • You're right : forgot a line while pasting ! – Countzero Jun 1 '12 at 14:38
  • 2
    you don't need this $() just event.target.id you are't referencing an object – Nikola Jan 4 '13 at 17:13
  • Why wrap it in Drupal behaviours? – ram4nd Feb 25 '15 at 11:19
  • 1
    Because it's considered best practice and prevents namespaces collisions, among other things. – Countzero Mar 2 '15 at 13:07
11

For versions of jQuery 1.8+, it seems you now must attach the .ajaxComplete function to the document, not the form or the view itself (see http://api.jquery.com/ajaxcomplete/)

The following worked for me on D7 with Jquery 1.10 and Views 7.x-3.8, where "your_view_id" is the machine name of the view set in the view's "Other" settings panel. There is a lot of other info in event, xhr and settings to key off of to determine if the ajax result is for the view you want, but this worked for my situation:

jQuery(document).ajaxComplete(function(event, xhr, settings) {
    if(typeof settings.extraData != 'undefined' && typeof settings.extraData.view_display_id != 'undefined') {

        switch(settings.extraData.view_display_id){

            case "your_view_id":

                console.log('your_view_id ajax results!');

                break;

            default:

                console.log('some other ajax result...');

                break;

        }
    }

});
| improve this answer | |
4

None of the given solutions worked for me with Drupal 7.24, jQuery 1.11 and Views 7.x-3.8.

What user1193694 suggested was not bad, but the settings object that I received didn't have the extraData parameter.

When parsing the settings object i saw that the settings.data propertiy contains 'view_name=' and your view's machine name, so thats what i am filtering for:

jQuery(document).ajaxComplete(function(event, xhr, settings) {

    // see if it is from our view
    if (settings.data.indexOf( "view_name=your_views_name") != -1) {

            console.log('your_view_id ajax results!');

    }
});

Replace 'your_views_name' with the machine name of your view.

| improve this answer | |

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.