WQ.Kevin WQ.Kevin - 3 years ago 131
Ajax Question

Rails Ajax Unexpected token < in JSON at position 0

I want my Index to change according to Price descending and Price ascending just like Amazon.

Right now, I send an ajax request to the site, with the new value of the select requesting the data. The site gets the data from database and sorts it. After that, my javascript redraws the cards in my index page with the sorted book response.

But when I console.log the result I get the whole html page.

This line of code below gives me the error:

var books = JSON.parse(result);



Unexpected token < in JSON at position 0
BookController.rb


How can I only get the @books?

Below is my code:

BookController.rb

def index
if params.dig("book", "title").nil? && params.dig("users", "university").nil?
@books = Book.where({title: params.dig("book", "title")})
.joins(:user).where(users: {university: params.dig("users", "university")})
elsif !params.dig("book", "title").nil? && params.dig("users", "university").nil?
@books = Book.where({title: params.dig("book", "title")})
elsif params.dig("book", "title").nil? && !params.dig("users", "university").nil?
@books = Book.joins(:user).where(users: {university: params.dig("users", "university")})
else
@books = Book.all
end
case params[:sort]
when "Price Descending"
@books.order(price_cents: "DESC")
when "Price Ascending"
@books.order(price_cents: "ASC")
else
@books.sort_by(&:created_at)
end
respond_to do |format|
format.html
format.json { render json: @books }
end
end


Book Index.html.erb

<select id="priceSelect">
<option value="Best Results" selected="selected">Best Results</option>
<option value="Price Descending">Price Descending</option>
<option value="Price Ascending">Price Ascending</option>
</select>
.
.
.
<div class="books-info">
<% @books.each do |book| %>
<div class="col-xs-12 selectable-card">
<%= link_to book_path(book.id) do %>
...
<% end %>
</div>
<% end %>
</div>

<script>
$('#priceSelect').change(function(){
$.ajax({
url: "books",
type: "GET",
data: {sort: $('#priceSelect :selected').val()},
success:function(ret){
console.log(ret);
var books = JSON.parse(ret);
var length = books.length;
var html = "";
for (var i = 0; i < length; i++) {
html += "<div class='col-xs-12 selectable-card'>";
html += "<a href='" + books[i].id + "'>" + books[i].name + "</a>";
html += "</div>";
}
$('.books-info').innerHTML = html
},
})
});
</script>


And lastly my routes.rb

resources :books do
resources :users
end

Answer Source

I think you're missing the accept header in your Ajax request so you're actually getting the HTML page back again.

Try:

$.ajax({
  dataType: 'json',
  ...
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download