Killerpixler
Killerpixler

Reputation: 4050

Rails ajax form submit

This is my layout, all in the authors_controller and Author model.

index.html.erb

<div class="row">
<div id="author-index" class="col-md-5">
    <%= render 'index'%>
</div>

<div id="author-modal" class="modal fade" role="dialog"></div>
</div>

_index.html.erb

<div class="row">
<%= form_tag authors_path, :method => 'get', remote: true do %>
<%= hidden_field_tag :direction, params[:direction]%>
<%= hidden_field_tag :sort, params[:sort]%>

<p>
    <%= link_to "New Author", new_author_path, remote: true, class: "btn btn-primary"%>

    Search for Author
    <%= text_field_tag :search, params[:search], onchange: "$(this).parent('form').submit();"%>
</p>
<% end %>
</div>

<div id="indexTable" class="row">
     #contains a table
</div>

My controller's show action:

    def index
    @authors = Author.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 10, :page => params[:page])
    respond_to do |format|
        format.html{}
        format.js{}
    end
end

When I look at the log of my server, all should work fine

Started GET "/authors?utf8=%E2%9C%93&direction=&sort=&search=Ali"

Processing by AuthorsController#index as JS

Parameters: {"utf8"=>"✓", "direction"=>"", "sort"=>"", "search"=>"Ali"}

Author Load (0.1ms) SELECT authors.* FROM authors WHERE (first_name LIKE '%Ali%' OR last_name LIKE '%Ali%') LIMIT 10 OFFSET 0

Rendered authors/_index.html.erb (2.3ms)

Rendered authors/index.js.erb (3.2ms)

Completed 200 OK in 7ms (Views: 5.2ms | ActiveRecord: 0.1ms)

However the page does not change. The form worked fine when I do it without remote: true.

Upvotes: 0

Views: 201

Answers (1)

markets
markets

Reputation: 7033

You should add a js.erb template named index into authors views folder (app/views/authors/index.js.erb). This template should have the javascript code that you want to execute (will be sent and evaluated on the client side) when the Ajax call is performed. More or less:

$("#author-index").html("<%= j(render 'index').html_safe %>")

Notice the format.js in the respond_to block; that allows the controller to respond to your Ajax request.

Upvotes: 1

Related Questions