Ok, i've been using ajax in my rails apps for quite some time. Somehow, in my first Rails 3.1 app I can't get the basics to work..
# application.js
//= require jquery
//= require jquery_ujs
# the form
= form_for @signup, :url => '/signup', :remote => true do |f|
= f.text_field :email, :class => 'email', :size => 26
= f.submit 'Notify me'
# the controller
def signup # route.rb has 'match '/signup' => 'controller#signup'
respond_to do |format|
format.js
end
end
# view: signup.js.erb
alert('wtf?');
Now, from what I can tell, submitting this form should trigger the alert box. It doesn't. The form submission does go through to the controller action, which does render the template:
Rendered teaser_pages/signup.js.erb (0.1ms)
Completed 200 OK in 8ms (Views: 7.2ms | ActiveRecord: 0.0ms)
Only no js is triggered.
The UJS helpers are loaded and functioning though (I think) because if i do..
link_to 'click me', '#', :confirm => 'confirmation box!'
..it will trigger a confirmation box as expected.
What could I be missing? Any direction to look would be appreciated.
Thank you, Erwin
UPDATE:
So it seems rails is proving the wrong content-type in the header, providing text/html
instead of text/javascript
. After some testing even:
render :js => "alert('AHAHAHAHA');", :content_type => 'text/javascript'
will still render a header with content-type text/html
When I run a fresh application with the same version of jquery-rails
it works. In this application it doesn't..
Where should I be looking?
I got the same problem. I set up a test app with same gemfile as well and got the same result as you described: it works in the newly created app but not in the old one. For the time being I set the content type header by hand before the actual render call.
respond_to do |format|
headers["Content-type"] = 'text/javascript'
format.js { render "the_template" }
end
This on the other hand did not change the content_type delivered correctly:
respond_to do |format|
format.js { render "the_template", :content_type => 'text/javascript' }
end
Hope this helps for the moment.
Did you get the real solution in the meantime?
UPDATE:
At least I found my real problem. I have a before_filter forcing the content_type to text/html which I added for testing some time ago and forgot to deactivate:
def set_header
response.headers["Content-Type"] = "text/html; charset=utf-8"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With