Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1: Server always processing as HTML, not JS

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.

like image 600
banhbaochay Avatar asked Aug 07 '26 09:08

banhbaochay


2 Answers

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?

like image 71
osahyoun Avatar answered Aug 09 '26 22:08

osahyoun


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

like image 38
Igor Kasyanchuk Avatar answered Aug 09 '26 23:08

Igor Kasyanchuk