1

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.

Xullnn
  • 405
  • 3
  • 17

1 Answers1

0

http://guides.rubyonrails.org/working_with_javascript_in_rails.html#an-introduction-to-ajax

As an example, here's some CoffeeScript code that makes an Ajax request using the jQuery library:

 $.ajax(url: "/test").done (html) ->
      $("#results").append html

I don't know how to do this, but I need to understand this so I am reading more about the jquery .ajax() function at

http://api.jquery.com/jQuery.ajax/

My idea is, if your .getJSON() is successful, you should append to your html page the result.

$.getJSON("/products", search_options, display_results)

I think that you can get your data from the AJAX response and you need to change your display_results() function

Please comment my post once you find the solution so that I can read it. I ll be reading the documentation and If I understand the problem I will update my answer

Post Request

based on the following video, I think you should create a post request as follows

  1. Your submit link will have an of id='submitLink', while the fields from the form will have id='name' and id='brand'

    var $name = $('#name')
    var $brand = $('#brand')
    // When the link is clicked you trigger the function
    $('#submitLink').on('click', function() {
       // Which creates a variable 
       var product = {
          name: $name,
          brand: $brand
       };
       $.ajax({
          type: 'POST',
          url: '/products',
          data: product,
          success: function () {
              // js code to run on success
          },
          error: function () {
              // js code to run on failure
          }
       });
    });
    
  2. You should be able to go to the network tab of your browser, find that post request and find in the body of your post request the form data you are submitting to the backend

How are parameters sent in an HTTP POST request?

Fabrizio Bertoglio
  • 5,890
  • 4
  • 16
  • 57
  • Thanks for following my question @Fabrizio Bertoglio. I do want to append the results in html page, but the returned data is an array with many js objects in it, can't directly append to a table. I need to convert it to something like `@products` then deal it with a loop. – Xullnn Sep 13 '17 at 15:10
  • @Caven ok that is easy, you just need to use a javascript loop for that array like in this guide and append every element to one of those fields https://www.w3schools.com/js/js_loop_for.asp – Fabrizio Bertoglio Sep 13 '17 at 15:24
  • I've tried this. But how to embed ruby code `<%= link_to "+", add_to_cart_product_path(product), method: :post %>` into javascript.[Here's the js code.] You can also check the partial in `views/products/_list_table.html.erb` – Xullnn Sep 14 '17 at 06:20
  • @Caven evaluate doing this as explained in the guide http://guides.rubyonrails.org/working_with_javascript_in_rails.html because your approach using `AJAX` is very complex, anyway the post request need s to be done with `jQuery.post()` that will create a `POST` request to `/products` and will include in the body of your request the `params` from `product`. Maybe it s easy watching this video https://www.youtube.com/watch?v=5nL7X1UMWsc – Fabrizio Bertoglio Sep 14 '17 at 06:38
  • I found a temporary solution: [datatables](https://datatables.net/). There is a brief introduction in [RailsCasts#340](http://railscasts.com/episodes/340-datatables). – Xullnn Sep 17 '17 at 10:24