Rerendering parts of a page with ajax

Hello guys

I have a index of people on my site. There the users can see all the people the site knows about. So I have a view people/index.html.erb. I still haven’t done pagination yet – I’m not sure how’s the best way to paginate in rails – but for now I’m just showing the top 10 (which should be the first page someday).

The feature I want to do right now is a filter based on people’s properties. For now I’ll do a check list with those properties. The user must tick out whatever she doesn’t want. I’m not sure how would be the best approach here.

I think I rather have it rendered via ajax, rather than reload the entire page everytime the user unticks something. But how is the best way to tackle this? I’m looking for outline of what would be a good practice. Using the knowledge of the features of javascript, jquery and rails I have come up with the following solution, although it doesn’t look like the ideal solution:

case 1) User first access to the page: Render the page like I do today, using index.html.erb.

case 2) User is viewing the page and unticks a property:

a) A javascript callback calls a method on people controller (via ajax) with the currently selected properties

b) the controller (after consulting the model) returns a list of people using json

c) javascript changes the HTML already rendered using the information received from such method

That solution doesn’t sound good to me because I’ll be duplicating some of the work I’ve done on index.html.erb when I write the javascript code to translate JSON into the proper HTML. Plus I don’t know how that approach would integrate with pagination afterwards. I think a better approach would be for the ajax to get the HTML for the part of the site that will be changed. That HTML must be generated in erb code, just like it was generated the first time the user visited my site. However, I’m unsure how to implement it that way. Could someone help me out?

All the best,

Rafael

Rafael,

For pagination I recomment kaminari.

For populating html via ajax without creating the DOM objects yourself I recommend something like EJS:
http://embeddedjs.com/

I’m not sure what the rails way would be, but that’s the way I reuse bits of HTML needed through a site.

You would basically do the AJAX call to populate some objects.

Then simply pass the objects to EJS and write out the HTML as you normally would.