Thursday 28 February 2008

Grails: Hacking paginate tag to make Ajax way

I one thing I miss in Grails is a remotePaginate Taglib (you can vote in Jira), today I'm going to hack paginate tag to make an Ajax paginate.

For this I have various options, I can modify the actual paginated taglib or the option I've chosen, hack with prototype observe the links generated by paginate tag.

To make easy, I've used observe tag, to capture clicks events, let's go with the example of list.gsp:

You have to wrap your list with div for this example 'ajax_wrap' to refresh with Ajax calls.
<div id="ajax_wrap">

<div class="list">
<g:render template="archive" collection="${archiveList}" var="archive"/>
</div>

<div class="paginateButtons">
<g:paginate action="list" total="${Archive.count()}" />
<g:observe classes="${['step','prevLink','nextLink']}" event="click" function="clickPaginate"/>
</div>

</div>
I've used g:observe to capture click events in generated links by g:paginate, and define a function handler clickPaginate that performs the Ajax calls.

Here function handler defnition:
function clickPaginate(event){
event.stop();
var link = event.element();
if(link.href == null){
return;
}

new Ajax.Updater(
{ success: $('ajax_wrap') },
link.href,
{
evalScripts: true
});
}
The Ajax call update the element 'ajax_wrap'.

With this you have an elegant way to make your list paginated effortlessly

12 comments:

Anonymous said...

Nice Post,

I tried your example and the pagination works like it should.

But I wonder why the pagination-buttons below my list wont update their appearance according to my clicks. If I load the page for the first time, the pagination-button "1" is down as expected, but if I click another one, nothing changes, "1" is still down, the current one not.

Do you have a workaround what I'm missing or doing wrong?

Regards, Fiesa

dahernan said...

Notice that g:paginate it's included in div ajax_wrap for this reason the buttons should be updated.

Anonymous said...

thx a lot for your (incredibly fast) advice, works as described!

Anonymous said...

perfection! thank you!

(although I kind of wanted to hack that taglib)

M

Ratn Dwivedi said...

Do i need to install prototype lib to make it working as you are using protype 'observe'

dahernan said...

@Dev - Prototype is already installed in Grails by default

Ratn Dwivedi said...

Thanks dahernan for quick reply .you rock!

modestymaster said...

dahernan++ Thanks for contributing this.

Anonymous said...

thanks a lot of your advice

Wolfgang Dümchen said...

it is, what i look for.
but please add the template and controller code. thx

smughal said...

Hello,
Can you please suggest how to do the same, i.e., hack paginate, using jQuery ?
Thanks
Shahzad

Amit Bhatt said...

I am unable to use <g:observe tag. Kindly suggest in which version it is defined or is there any additional plugin required for the same.

I want to use <g:paginate kind of AJAX Call as I dont want to refresh entire screen