2

Still trying to fix my ajax to work with the controller. Now I get this error message:

response SyntaxError: Unexpected token j ,  xhr[object Object] ,  STATUS parsererror

config.routes

resources :books do 
    member do 
      get '/last_chapter/', to: 'chapters#last_chapter', as: 'last_chapter', defaults: { format: 'json' }
    end
    resources :chapters
  end 

chapter controller

def last_chapter
        @last_chapter = Chapter.order(created_at: :desc).limit(1)
        respond_to do |format|
            format.json
        end
    end

last_chapter.json

json.extract! @last_chapter, :id, :title, :characters, :created_at, :updated_at

script.js

$.ajax({
      type: "GET",
      url: '/books/103/last_chapter.json',
      contentType: "application/json",
      success: function(data) {
        console.log('JAAAA ENDELIG FUNKER DET');
        $("body").html(data);
      },
      error: function(xhr, status, response) {
        console.log('response ' + response +  ' ,  xhr' + xhr +  ' ,  ' + 'STATUS ' + status)}
    });

Feel like I have tried everything. Please let me know if you need anymore information! :)

1 Answer 1

1

I think your problem lies in the routes. Here is what I would do:

resources :books do
  get :last_chapter, on: :member
end

books_controller.rb

def last_chapter
  @last_chapter = Book.find(params[:id]).chapters.last
  respond_to do |format|
    format.json do
      render json: { does_it_work: :yes }
    end
  end
end

I assume the following model:

class Book < ActiveRecord::Base
    has_many :chapters
end
Sign up to request clarification or add additional context in comments.

13 Comments

How would you do the url for the ajax? For now it can't find "/last_chapter" because I need the last chapter id.
I would leave the ajax call as it is. What's the point of last_chapter action then if you need to know the id of it? You need to provide a book_id, and then this action should return the last chapter of this book!
Also, when I add in the url manually (with the chapter id) like this. url: '/books/103/chapters/206/last_player.json', I get this error: ` Error in response to storage.get: TypeError: Cannot read property 'style' of null at Object.callback (chrome-extension://kchdfagjljmhgapoonapmfngpadcjkhk/js/scripts.js:24:42) at chrome-extension://kchdfagjljmhgapoonapmfngpadcjkhk/js/scripts.js:11:21`
If I leave the url as it was it gives me this error: 404 (Not Found)
Do you have a book with id 103?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.