Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get UJS to work in Rails 3.1

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?

like image 545
ErwinM Avatar asked Nov 13 '22 17:11

ErwinM


1 Answers

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
like image 107
jo. Avatar answered Nov 17 '22 07:11

jo.