Updating table data in rails using ajax

ajax, jquery, ruby, ruby-on-rails, ruby-on-rails-3

Solution

Try to write some partial and add the partial data to tbody

for example:

controller:

def show
    #displaying filtered results
    @query = (db query)
    #pass @query to index.html.erb and update only the tbody with id=content which takes @query
    render :partial => 'show_partial'

  end

_show_partial.html.erb:

<% if @query%>      
      <% @query.each do |query| %>
          <tr><td><%= query.sr_number %></td><td><%= query.from %></td><td><%= query.title %></td></tr>
      <% end %>
<% end %>

and then

//ajax call handler in index.html.erb
$("#search_form").submit(function(){
    var dataSet = $(this).serialize();
    $.ajax({
        type: "POST",
        url: $(this).attr("action"),
        data: dataSet,
        success: function(data){
              $('#content').html(data)
        }
    });
    return false;
});

I think it may solve your problem

Problem

I have only one view index.html.erb which displays all employee names and all the details in the database. I have a search form wherein the search results should be updated in the table tbody with id "content". my index.html.erb renders fine the first time. Here is my index.html.erb ``` //my view index.html.erb <%= form_for :query, :url => { :controller => "home", :action => "show" }, :html =>{:id => "search_form"} do |f|%> <div> <p>Enter the search keywords:</p> <input type="text" id="query_search_key" name="query[search_key]"/> <%= f.submit "Search" %> <p>Raised By : <select style="width:300px" id="query_raised_by" name="query[raised_by]"> <option value="-1" selected>Select member</option> <% @m_n.each do |m_n| %> <option value="<%= m_n.full_name %>"><%= m_n.full_name %></option> <% end %> </select> </div> <% end %> <div> <table id="table" class="display"> <thead> <tr><th>Sr Number</th><th>Raised By</th><th>Title</th></tr> </thead> <tbody id="content"> <% if @query%> <% @query.each do |query| %> <tr><td><%= query.sr_number %></td><td><%= query.from %></td><td><%= query.title %></td></tr> <% end %> <% end %> </tbody> </table> </div> //ajax call handler in index.html.erb $("#search_form").submit(function(){ var dataSet = $(this).serialize(); $.ajax({ type: "POST", url: $(this).attr("action"), data: dataSet, success: function(data){ //update the contents of tbody with id content } }); return false; }); ``` Here is my controller ``` //my controller class HomeController < ActionController::Base def index @m_n = (db query getting member names) #displaying al records @query = (db query) end def show #displaying filtered results @query = (db query) flash[:notice] = "success: "+ no_of_results + " were found" render :partial => 'search' end end ``` From show action I want to update only the table tbody with id "content" in index.html.erb using @query object.

Original source