10

I am not familiar with ajax nor ruby on rails.I've been self learn to do project.

Now I face a problem,I want to use ajax to retrieve data from controller.

I'm not sure how to write the url part:

$.ajax({
  type:"GET",
  url:"books",
  dataType:"json",
  success:function(result){
    alert(result);
  }
})

books is the name of my controller(book is one of my table)

this code works,but instead of retrieve all data from books,I only want a part of it. say some data in action test in my books controller

def test
  @test=books.find.last
  respond_do |format|
    format.html
    format.json {render ;json=>@test}
  end
end

but when I change url to books/test,I'll get a error message say 404 not found in console log.

How can I retrieve part of controller data?thanks in advance

1
  • Did you mention test action in routes.rb? can you share your routes.rb too? Commented Sep 11, 2014 at 5:12

1 Answer 1

14

Well what your trying to do here is create a non RESTful route called test. So you'll need to add this into routes.rb (see here for more info):

resources :books do
  collection do
    get 'test'
  end
end

If you want, you could pass your parameters like this:

$.ajax({
  type:"GET",
  url:"books/test",
  dataType:"json",
  data: {some_parameter: 'hello'},
  success:function(result){
    alert(result);
  }
})

Which you could then use in the test method like this:

def test
  some_parameter = params[:some_parameter]
  # do something with some_parameter and return the results

  @test=books.find.last
  respond_do |format|
    format.html
    format.json {render json: @test}
  end
end
Sign up to request clarification or add additional context in comments.

5 Comments

how exactly your URL is going to call test method in books controller?
Sorry I left that out. Updated my answer.
You might want to change // do something with some_parameter and return the results to # do something with some_parameter and return the results because that's not a valid comment in Ruby? And also if you can return a JSON in respond_to block.
whoops! mixing up php and ruby code! fixed the comment. and added in your code to return the last book. fyi you had a semicolon in there for some reason before 'json'.
Great! I am sorry but I am not the one who's created this OP. :)

Your Answer

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