Ngoral Ngoral - 1 month ago 4
Javascript Question

Rails code for format js do not work

I'm trying to implemet a complex task, and faced with a problem, that my JS code do not work when called from

format.js
.

I have a link with such code:
= link_to new_user_support_letter_path, {:id => 'contact-us', :remote => true }


In my
user_support_letters_controller.rb
:

def new
@letter = UserSupportLetter.new
respond_to do |format|
format.js {}
format.html
end
end


In
new.js.erb
:

alert("rrr");


So, when I click a link nothing happens.

Meaningful logs for clicking a link:

I, [2016-10-19T21:47:41.130608 #1] INFO -- : Started GET "/user_support_letters/new" for 172.18.0.6 at 2016-10-19 21:47:41 +0000
I, [2016-10-19T21:47:41.150411 #1] INFO -- : Processing by UserSupportLettersController#new as JS
I, [2016-10-19T21:47:41.269853 #1] INFO -- : Rendered user_support_letters/new.js.erb within layouts/application (0.1ms)
I, [2016-10-19T21:47:41.344629 #1] INFO -- : Rendered application/_support_email.slim (0.1ms)
...


Can anybody tell what I'm doing wrong? Thanx!

Answer

To get this to work you need to set layout to false and declare the content_type you're using.

From what I know/have read this is standard behaviour in rails. Here is a similar post discussing it with a link to a bug log. http://stackoverflow.com/a/1170121/3366016

Change your controller action to this:

  def new
    @letter = UserSupportLetter.new
    respond_to do |format|
      format.js { render layout: false, content_type: 'text/javascript' }
      format.html
    end
  end

By default it will try to load in the current layout. By setting false you are disabling it and just telling it to render without a layout.

Comments