Title says it all in views 3 is there a short snippet of javascript that will trigger an ajax view refresh.
This is what I have scrapped together so far from ajax_view.js and views_autorefresh, but as soon as the "data" parameter is uncommented it flops and the page will timeout after the js is triggered.

if (Drupal.settings && Drupal.settings.views && Drupal.settings.views.ajaxViews) {
  $.each(Drupal.settings.views.ajaxViews, function(i, settings) {

    var selector = '.view-dom-id-' + settings.view_dom_id;
    this.$view = $(selector);

    // Retrieve the path to use for views' ajax.
    var ajax_path = Drupal.settings.views.ajax_path;

    // If there are multiple views this might've ended up showing up multiple times.
    if (ajax_path.constructor.toString().indexOf("Array") != -1) {
      ajax_path = ajax_path[0];
    }

    $.ajax({
      url: ajax_path,
      type: 'GET',
      //data: settings,
      success: function(response) {
        console.log('success');
        console.log(response);
      },
      error: function(xhr) {
        console.log('error');
        console.log(xhr);
      },
      dataType: 'json',
    });

  });
}

Comments

drewish’s picture

I had a view with a couple of items that I needed to refresh in place. It had no pagination, just the 3 most recent items so I enabled AJAX on the view and added this little snipped of JS to refresh it every 30 seconds.

(function ($) {
  Drupal.behaviors.recentMeAutoRefresh = {
    attach: function (context, settings) {
      jQuery.each(Drupal.views.instances, function(i, view) {
        if (view.settings.view_name == "recent_me_items") {
          view.$view.once('view-refresher', function() {
            // Remove the pager_element so views doesn't try to scroll to the top
            // on refresh.
            delete view.settings.pager_element;
            // Construct a hidden refresh link.
            var html = '<a href="' + view.settings.view_path + '" class="view-refresher" style="display:none">Refresh</a>';
            view.$view.append(jQuery(html).each(jQuery.proxy(view.attachPagerLinkAjax, view)));
          });
          return false;
        }
      });
    }
  };

  // Schedule a refresh for every 30 seconds... and say hello to server load.
  setInterval(function() { jQuery('.view-refresher').click(); }, 30000);
})(jQuery);
mustanggb’s picture

Status: Active » Closed (won't fix)
imclean’s picture

Issue summary: View changes

This keeps coming up in searches so here's an easy method for refreshing an ajax view using the event RefreshView.

See first post for context.

var selector = '.view-dom-id-' + settings.view_dom_id;
$(selector).triggerHandler('RefreshView');

Also see .trigger() if you'd prefer.

rob c’s picture

$(selector).triggerHandler('RefreshView');

is introduced in views 3.8. (for everybody that's like me searching MAO about this). (but awesome this is in! Now we can build some really Great after ajax stuff etc etc.)

rerooting’s picture

Nice!

I had views rendering in multiple blocks and wanted to refresh the first one, and thus I was able to improvise and do this:

  var views = settings.views.ajaxViews;
  var dom_id = views[Object.keys(views)[0]]['view_dom_id'];
  var selector = '.view-dom-id-' + dom_id;
  $(selector).triggerHandler('RefreshView');

This could be handy in case you want to trigger the ajax reload on multiple views as well, since this allows you to iterate through the ajaxView object's properties numerically (which will be your views). The property name is views_dom_id:s89df98sd7f89sd7 if you wanna deal with the hot mess that way as well with a string method. I'm also noticing that you can do things here like manipulate the views argument... hmm!

imclean’s picture

Here's an example looking for a specific display ID and adding some arguments:

// Look through all the ajax views
for (var viewName in settings.views.ajaxViews) {

  // Find the member_selection view
  if (settings.views.ajaxViews[viewName].view_display_id == 'myview_display') {

    var dom_id = settings.views.ajaxViews[viewName].view_dom_id;     
    var view_selector = '.view-dom-id-' + settings.views.ajaxViews[viewName].view_dom_id;

    // Settings variable to simplify things.
    var viewSettings = settings.views.ajaxViews['views_dom_id:' + dom_id];

    // Set the contextual filter (args) to the date and category
    viewSettings.view_args = itinerary_date + '/' + itinerary_category;

    // Apply to views settings.
    Drupal.settings.views.ajaxViews['views_dom_id:' + dom_id] = viewSettings;

    // Refresh view
    $(view_selector).triggerHandler('RefreshView');
         
    } // myview_display

} // ajaxViews loop
pal4life’s picture

Where do we add this code on? Inside the view or in a separate js file that gets loaded on the view page

var views = settings.views.ajaxViews;
var dom_id = views[Object.keys(views)[0]]['view_dom_id'];
var selector = '.view-dom-id-' + dom_id;
$(selector).triggerHandler('RefreshView');

imclean’s picture

@pal4live

In your own module or theme's javascript. Don't forget behaviors etc.

https://www.drupal.org/node/756722

trw’s picture

Thanks to @imclean and @rerooting for great examples! These have gotten me very close to where I need to be. I'm stuck on the last step. I'm getting the dom_id of the view (it's the first and only on the page) but I can't quite figure out how to get the argument to change what shows in the view. In this example, I'm updating the default value in view_args from 8 (set in Contextual Filters) to 9. All of that seems to be happening, but the view doesn't every seem to update.

drupal_add_js ("
   jQuery(document).ready(function () {
        jQuery('.refresh-help a').on('click', function (e) {
            var contentId = $(this).attr('id');
            var views = Drupal.settings.views.ajaxViews;
  			var dom_id = views[Object.keys(views)[0]]['view_dom_id'];
  			var args = Drupal.settings.views.ajaxViews['views_dom_id:' + dom_id].view_args; //using this to verify
    		        Drupal.settings.views.ajaxViews['views_dom_id:' + dom_id].view_args = contentId;
  			var selector = '.view-dom-id-' + dom_id;
			jQuery(selector).triggerHandler('RefreshView');
			alert(contentId + ' | ' + selector + ' | ' + args);	//displays the values so I know that values have updated.
        });
    });
   ",'inline');
trw’s picture

Hi all,

I've been digging further and I think the place I'm stuck is that I don't understand in this line:

jQuery(selector).triggerHandler('RefreshView');

where "RefreshView" is defined. In all of the examples I've seen, triggerHandler() is calling something that was previously defined.

Any help appreciated.

Tim

imclean’s picture

RefreshView is defined in Views. #4 mentions it was introduced in Views 3.8.

trw’s picture

Thanks, @imclean. I missed that. Do you have any ideas for troubleshooting this? It really sea like I've got we're thing but the last step working and am just stumped.

trw’s picture

I'm hoping someone can jump in and help me figure out how to troubleshoot this. Feeling like I've hit a brick wall even though it seems like I'm really close!

leolandotan’s picture

I'm also trying to refresh a view after an ajax popup form submits but I cant seem to make the jQuery code work. I just tried to trigger the refresh when I click the table because initially I want it to be part of an ajax_command array.

function mymod_user_edit_popup($js = NULL, $uid) {

  // some additional codes here

  $output = ctools_modal_form_wrapper('mymod_users_edit', $form_state);

  if (!empty($form_state['executed'])) {
    //display the system message ajax style
    $output = mymod_close_popup_message();
    //reload the table ajax style
    $output[] = ajax_command_replace('#user-list', mymod_user_list());
  }

  print ajax_render($output);
  exit;
}

I'd like to replace this line $output[] = ajax_command_replace('#user-list', mymod_user_list()); to a line that calls the jQuery file but right now i'm just keeping it simple but still doesn't seem to work.

This is the simple jQuery code that doesn't work but the console "passed" is always printed.

(function($) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
    	$('table').click(function() {
      	$('.view-dom-id-403402eee35f68cd32fe87b45702dc63').triggerHandler('RefreshView');
      	console.log('passed');
    	});
    }
  };
})(jQuery);

Anything I missed here?

anybody’s picture

This blog article I've just written about it shows implementation of a Views AJAX refresh via JavaScript (jQuery) or even PHP and may help you and others in the future:

http://julian.pustkuchen.com/en/drupal-7-api-trigger-views-ajax-refresh-...

Happy coding!

awasson’s picture

CAUTION: The link in the comment by Anybody #15 leads to a page that is affected by a phishing attack. Do not follow it.

Julian: You better have a look into what that's about.

EDIT: It looks like this isn't a phishing attempt after all but maybe the result of an overly aggressive advertisement mechanism on the blog.

anybody’s picture

@awasson: I've sent you a pm! It's my private blog and there should be no phishing. Please lets have a quick conversation. The link should definitely be clean!

Virus / security checks are all absolutely okay, see:
https://www.virustotal.com/de/url/71dcea9b401a496a8da9a8a76f06f2c858c176...
http://scanurl.net/?u=http%3A%2F%2Fjulian.pustkuchen.com%2Fen%2Fdrupal-7...

awasson’s picture

Sounds good.

phponwebsites’s picture

When i tried to refresh view in jquery, pager in views is run automatically. how to stop running of pager in views?

core44’s picture

having the same issue as phponwebsites above. When using

$(selector).triggerHandler('RefreshView');

my view refreshes nicely, but the pager also triggers and changes the view to the next page.

edodusi’s picture

I found a hack that solves the pager issue for me https://www.drupal.org/node/2199049#comment-10265551

maximpodorov’s picture

New module is released for views reloading: https://www.drupal.org/project/views_refresh

ugintl’s picture

Has anybody landed on Ajax Views Refresh module? This is a very much needed module but unfortunately not for D7. May be someone who knows coding can copy some of the code and reuse it for D7

ugintl’s picture

I have also asked a question on statckexchange