Peter Tretiakov
Peter Tretiakov

Reputation: 3410

Update page with AJAX on link click

I'm making a Debt management app and I have @opened_debts and @all_debts (opened and returned debts) in my controller.

By default I load only @opened_debts on page. But also I have a link for showing all debts on a page.

<a href="#" id="show_all_debts">Show all debts</a>

I want page to reload debts_div with @all_debts after clicking this link.

If I make a <script> tag with click event in the bottom of a page to load it with

$('#debts_div).replaceWith('<%= j render @all_debts %>');

Rails in fact renders all debts and make them invisible for user until he click the link. But it makes page loading slower with all this huge script.

Can I load this list without rendering it on a page until user clicks link?

Thanks in advance!

Upvotes: 1

Views: 626

Answers (1)

devanand
devanand

Reputation: 5290

use rails_ujs

<%= link_to "Show all depts", model_path(), :remote => true %>

then your request will be sent as ajax. create a view for js with

_index.html

<div>some code</div>

inside index.html.erb to make DRY

<%= render :partial => 'index.html' %>

index.js.erb to make DRY

$('#debts_div).replaceWith('<%= j( render :partial => 'index', :format => :html ) %>');

that should work

Upvotes: 2

Related Questions