I have a Product
model in my rails app.
I want to implement a live search form in products/index.html.erb
with AJAX
.
I succeed in getting search results with AJAX with this:
<script>
var $search_field = $("#key_word");
var $table_body = $("#products_body");
$search_field.keyup(function(){
var search_keyword = $search_field.val();
var search_options = {
utf8: "✓",
key_word: search_keyword
}
function display_results(data) {
console.log(data); // Testing if I can get response correctly
};
$.getJSON("/products", search_options, display_results)
}) ;
</script>
Inspecting dev tool's console, local server do send back the right search results when typing different words.Here's a screenshot of dev tool console
Previously I implemented a simple search form and create partial views/products/_list_table
to handle the table. In products_controller I defined @products
so it can be used in partial.
Here is the index
in products_controller:
def index
if params[:key_word].present?
@products = Product.find_by_sql("# some sql code here")
else
@products = Product.all
end
set_price(@products)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products}
end
end
And Here is the partial:
<thead>
<tr>
<th>Name</th>
.
.
.
<th>Manu</th>
</tr>
</thead>
<tbody id="products_body">
<% @products.each do |product| %>
<tr>
<td><%= product.name%></td>
<td><%= product.brand%></td>
.
.
.
</tr>
<% end %>
</tbody>
But I don't know how to pass the ajax search result(in this case is the data
followed display_result()
function) to the partial.
I've tried using $.each()
loop to generate a new form in scripts, but it makes code tedious. There should be some ways that can send the ajax data to partial and generate the table in a drier way.
Question: In this case, how to send data which I get from ajax request to partial _list_table
, then use it to generate a products table ?
Could someone help me? Thanks.