I am using ajax to update the search result of a product in my ruby-on-rails project. The request is not sent to the right controller method when the form is submitted at the first time, but works fine since the second click. I am still new to rails and ajax, please help. Thanks!
Here are the relative codes:
on view:
<form id="search-product">
<div class="container">
  <div class="row">
    <div class="col-md-1">Search by:</div>
    <div class="col-md-1">
      <select name="searchOption">
        <option value="UPC">UPC</option>
        <option value="Vendor_SKU">Vendor SKU</option>
      </select>
    </div>
    <div class="col-md-3">
      <form><input type="text" name="searchValue"></form>
    </div>
    <div class="col-md-2">
    <input type="submit" value="Search" >
    </div>
  </div>
</div>
</form>
on controller:
def search
    search_option = params[:searchOption]
    search_value = params[:searchValue]
    if search_option === 'UPC'
      @product = Product.find_by(upc: search_value) if search_value.length === 12
    elsif search_option === 'Vendor_SKU'
      @product = Product.find_by(vendor_sku: search_value) unless search_value.empty?
    end
    @b_found = false
    @b_found = true if @product
    respond_to do |format|
      format.js
    end
  end
I have configured the route to direct the request to the controller action.
In search.js:
<% if @b_found %>
  $('#product_search_result').html("<%=escape_javascript render('show', product: @product) %>");
<% else %>
  $('#product_search_result').html("<%=escape_javascript 'No matched product was found!' %>");
<% end %>
in application.js:
$("#search-product").submit(function(e) {
    e.preventDefault();
    var valuesToSubmit = $(this).serialize();
    $.ajax({
      type: "POST",
      url: "/search_product",
      data: valuesToSubmit,
      dataType: "script",
    });
  })
I tried putting after document.ready but did not make a difference.
 
    