Bharath
Bharath

Reputation: 15

AJAX request Rails 3.1 not rendering javascript

I am a newbie to Rails. I have a program which does basic AJAX functionality in RAILS. The link TEST when clicked, would execute the test path in the controller, which executes the test.js.erb. But I see that rendered in server logs, but dont see the alert message though.

index.html.erb:

<%= link_to 'TEST', test_path, :remote => true %> <br>

test action:

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

test js.erb:

"alert('Hello Rails');"

Server log:

Started GET "/test" for x.x.x.x at 2013-06-30 11:34:37 -0700 Processing by DefaultController#test as JS
Rendered Default/test.js.erb (0.3ms) Completed 200 OK in 2ms (Views: 2.1ms | ActiveRecord: 0.0ms)

If I change the code to render the js directly from the controller action, like shown below, , I see the alert message.

  def test
     render :js "alert('Hello Rails');"
  end

But I want the js to be executed in a separate js file. Can someone help me with what I am doing wrong, and how to have it executed as a part of test.js.erb ?

Upvotes: 0

Views: 433

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

Joe Half Face is right,

"alert('Hello Rails');"

should be:

alert('Hello Rails');

keeping this in quotes will take it as a string and so there is no javascript code to run, everything in the js file imagine it as beeing inside of javascript tags:

<script type="text/javascript">
  content of js.erb file
</script>

Upvotes: 1

Related Questions