Reputation: 719
I don't know how I am going to ask or start my question but what I want is to reuse my AJAX view to other page. I have an existing AJAX view, when I click a link from my sidebar I want to render a new page then call the AJAX view.
Please see example code below. I hope you understand my problem.
def index
@items = Item.all
end
def category
@categories = Category.all
end
<%= @items.count %>
<div class="ajax_form"></div>
$(".ajax_form").html("<%= escape_javascript(render 'category') %>");
<%= @categories.count %>
After I click the link from the sidebar, I want to call the ajax also without recreating it.
<a href="<%= items_path %>" >
click_me
</a>
Upvotes: 0
Views: 48
Reputation: 224
You can do this by sending an extra parameter like this:
<a href="<%= items_path %>?fetch_category=true" >
click_me
</a>
Change your index action of items controller
def index
@items = Item.all
@fetch_categories = params[:fetch_category] unless params[:fetch_category].blank?
end
And finally in your views/items/index.html.erb add these lines at the bottom of file.
<script>
$(function(){
<% if @fetch_categories %>
$.ajax({
url: "<%= others_category_path %>",
type: "GET",
data: {}
});
<% end %>
});
</script>
Upvotes: 1