1

How to create ajax in next example:

In controller:

def index
    if params[:p] == "one"
        @record = "Hello, 1!"
    elsif params[:p] == "two"
        @record = "Hello, 2!"
    else
        @record = "something else"
    end
end

In view (hellos controller, index action):

<%= link_to "One", hellos_path(:p => "one") %>
<%= link_to "Two", hellos_path(:p => "two") %>
<%= render :partial => 'record' %>

Partial _record.html.erb:

<%= @record %>

That's all. All actions in index controller and only params are changing. I don't want to reload full page - only record partial with new controller variable.

How to "AJAXize" it? :)

1 Answer 1

4

1- Add :remote => true to your links:

<%= link_to "One", hellos_path(:p => "one"), :remote => true %>

2- create a view index.js.erb with:

$("#your_div").html("<%= render :partial => "record" %>")

3- create a div with the id your_div in your index.html.erb. This div will be populated with the @record object.

Sign up to request clarification or add additional context in comments.

7 Comments

In 3rd step, am I need to add something like <div id="your_div"></div> and remove <%= render :partial => 'record' %> from view?
You need to create the div like you said. It is up to you if you want to leave the render partial so that default index page will present it.
Yep, but when I click link, I'm getting "Completed 200 OK", but it's not present in browser :(
$("#your_div").html("<%= j render ("record") %>") this works for me! :) tnx )
Ok, it's rendering, but without params :( If I'm in index page and clicking on "One" link, I'm getting this from my controller @record = "something else" :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.