do_Ob
do_Ob

Reputation: 719

render the view then call the existing AJAX view

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.

items_controller.rb

def index
    @items = Item.all
end

others_controller.rb

def category
    @categories = Category.all
end

views/items/index.html.erb

<%= @items.count %>
<div class="ajax_form"></div>

views/others/category.js.erb

$(".ajax_form").html("<%= escape_javascript(render 'category') %>");

views/others/category.html.erb

<%= @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

Answers (1)

Prity
Prity

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

Related Questions