Nadeem Yasin
Nadeem Yasin

Reputation: 4534

vanilla javascript rendering plane text RAILS

I have been using vanilla javascript and im just rendering a simple alert message but it renders the JS code as plane string in view. Here is my code

def index
render :js => "alert('Hello Rails');"
end

It renders the same string "alert('Hello Rails');" for me in view instead of a alert message. Im in Rails 3 and as Rails guide the code looks ok.

Any answers would be appreciated. Thanks

Upvotes: 0

Views: 1137

Answers (2)

dimuch
dimuch

Reputation: 12818

Compare two following snippets:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script>
    alert('Hello Rails');
    </script>
</body>
</html>

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    alert('Hello Rails');
</body>
</html>

First one generates alert message, second just shows the the string. Browsers do not execute JS code unless it is wrapped with <script> tag. jQuery ajax calls in the @Erez answer also wrap response with <script> internally.

So if you access your action directly try to wrap it with <script> , or, better, use javascript_tag helper (http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-javascript_tag)

Upvotes: 2

Erez Rabih
Erez Rabih

Reputation: 15788

You are rendering JS ok. The problem is with the browser which receives this JS and displays it as plain text.

Try sending an AJAX request with (using JQuery here):

$.ajax(url: '/index/url', type: 'GET', dataType: 'script')

Note that the dataType is set to script, meaning JQuery will execute the returned text as JS.

The short version for this would be

$.getScript('/index/url');

Upvotes: 0

Related Questions