3

I'm using rails 3.1.3. I want to use js.erb file as follow steps:
1. Create test action in posts controller:

def test
    respond_to do |format|
        format.js
    end
end  

2. Define this action in routes.rb:

resource :posts do
    collection do
        get 'test'
    end
end

3. Create test.js.erb file:

$('#abc').append('<h1>something</h1>');

4. In the index.html.erb file:

<div id='abc'></div>
<%= link_to "Test", test_posts_path, :remote => true %>

However, I run and click to test link, it go to blank page with url http://localhost:3000/posts/test and the log server is:

Started GET "/posts/test" for 127.0.0.1 at Sat Feb 11 18:04:36 +0700 2012
Processing by PostsController#test as HTML

So, server not process as JS, jQuery in test.js.erb file is not executed. Can you explain for me why server process as HTML while in controller I define respond_to format.js?
I assume all responds in project are defined to format.html so my test action cannot respond to JS? If right, can I change it?
Thank you very much

UPDATE: In assets/javascripts/application.js need lines to use:

//= require jquery
//= require jquery_ujs

Then it works.

prusswan
  • 6,853
  • 4
  • 40
  • 61
banhbaochay
  • 299
  • 1
  • 5
  • 14

2 Answers2

7

Are you sure you have gem 'jquery-rails' in your Gemfile and <%= javascript_include_tag "jquery", "jquery_ujs" %> in your layout or index.html.erb template?

osahyoun
  • 5,173
  • 2
  • 17
  • 15
  • 1
    Oh, thank you. In rails 3.1.3, gem 'jquery-rails' is default. In assets/javascripts/application.js, I insert //= require jquery_ujs and it works. That's my fool when I deleted it – banhbaochay Feb 11 '12 at 12:45
  • This solved a similar problem for me after hours of searching! Thanks. – GMA Jun 01 '13 at 17:13
2

Try <%= link_to "Test", test_posts_path(:format => :js), :remote => true %> to see what happen

Igor Kasyanchuk
  • 766
  • 6
  • 12