0

When I add my rails code into my jquery I have this problem:

Uncaught SyntaxError: Unexpected token <

Here my controller:

class WelcomeController < ApplicationController
    def index
        @a = "12345"
    end
end

My index.js

jQuery(function($) {
    $(document).ready(function($) {
        var a = <%= @a %>
        var url = "http://www.google.com"
        console.log(a)
    }); 
});

I don't know how to fix that, please help me!

6
  • 1
    Your index.js file isn't rendered by erb. Put it in your views in index.js.erb instead and create appropriate action for it. Commented Apr 13, 2015 at 8:47
  • var a = '<%= @a %>' Use this. Wrap it in quotes Commented Apr 13, 2015 at 8:47
  • 2
    @ShaunakD it won't help. Commented Apr 13, 2015 at 8:48
  • when I change index.js to index.js.erb, I have new error :Uncaught SyntaxError: Unexpected token var Commented Apr 13, 2015 at 8:56
  • 1
    missing ; in your js code. I suggest you read something about javascripts syntax Commented Apr 13, 2015 at 9:05

1 Answer 1

2

Change the filename to index.js.erb so that rails understands that you want to insert ruby code inside your javascript.

Also fix your javascript code:

jQuery(function($) {
    $(document).ready(function($) {
        var a = "<%= @a %>";
        var url = "http://www.google.com";
        console.log(a);
    }); 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.