hrsetyono
hrsetyono

Reputation: 4464

Rails ujs - manual AJAX renders HTML template instead of JS template

I have a Products page that has search bar. For every keyup I want to update the Product list.

My index.html.erb lists ALL products while index.js.erb will repopulate the list with the searched product.

The problem is: Rails always returns the HTML template instead of the JS template.

So, when I checked the NETWORK tab in Chrome, I get the response but it contains the HTML template.

Here's my simplified code:

// js
$("#search").on("keyup", function() {
  var query = { search: $(this).val() };
  $.get("/products", query);
});

My controller is just a simple where clause:

# products_controller.rb
def index
  if params[:search]
    @products = Product.where("( LOWER(name) LIKE LOWER(?)", "%#{ params[:search] }%")
  else
    @products = Product.all
  end 

  respond_to do |format|
    format.html
    format.js
  end
end

The JS template is still an inspect

// products/index.js.erb
console.log("<%= @products.inspect %>");

Thanks.

Upvotes: 1

Views: 264

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

It's likely a result of showing the layout in your ajax response:

#app/controllers/products_controller.rb
Class ProductsController < ApplicationController
   def index
      ...
      respond_to do |format|
         format.js   { render layout: !request.xhr? }
         format.json { render json: @products.to_json }
      end
   end
end

If you'd like to receive just pure product data, you'll want to use JSON as follows:

$.get("/products", query, dataType: "json");

This will give you the ability to receive the json object, which will just be a pure set of data:

$.get("/products", query, dataType: "json", function(data){
   //json data will be here
});

Upvotes: 2

Related Questions