views:

58

answers:

1

I have already implemented some AJAX pagination in my Rails app by using the example code for the will_paginate plugin--which is apparently using Prototype.

But if I wanted to switch to using jQuery for future additions, I really don't want to have the Prototype stuff sitting around too (yes, I know it's possible). I haven't written a lick of JavaScript in years, let alone looked into Prototype and jQuery... so I could use some help converting this bit into jQuery-compatible syntax:

document.observe("dom:loaded", function() {
  // the element in which we will observe all clicks and capture
  // ones originating from pagination links
  var container = $(document.body)

  if (container) {
    var img = new Image
    img.src = '/images/spinner.gif'

    function createSpinner() {
      return new Element('img', { src: img.src, 'class': 'spinner' })
    }

    container.observe('click', function(e) {
      var el = e.element()
      if (el.match('.pagination a')) {
        el.up('.pagination').insert(createSpinner())
        new Ajax.Request(el.href, { method: 'get' })
        e.stop()
      }
    })
  }
})

Thanks in advance!


Edit: Nick Craver's answer got me 90% of the way there, so I just had to pick up enough jQuery to make the HTML element substitution. In place of the line where Nick had $.get($(this).attr("href"));, put this line:

$.get(this.href, null, function(data){ $(this).html(data); }, 'html');
+1  A: 

You can shorten this down a bit in jQuery to:

$(function() {
  $('.pagination a').live('click', function(e) {
    $(this).parent('.pagination')
           .append("<img src='/images/spinner.gif' class='spinner' />");
    $.get($(this).attr("href"));
    return false;
  });
});

I'm not entirely sure about new Ajax.Request(el.href, { method: 'get' }) though, is this a script being requested? It looks like nothing's being done with the content after return.

Nick Craver
I'm not that confident with Ruby but the site he linked to has `format.js` somewhere. Which should mean that `[actionName].js.erb` is called which should return some js-code which Prototype automagically evals if a javascript related mime-type http://api.prototypejs.org/ajax/ajax/request.html is set. But without that piece of code we are out of luck
jitter
Awesome! I'll try fitting this in momentarily...Indeed there is a format.js section included on that page--it's no more than `render :update do |page| { page.replace 'results', :partial => 'search_results' }`. So I think Rails is just rendering the html/erb partial which is replacing the entire "results" div, but I'm not sure how the JavaScript callback is doing that.
ewall
ewall