Trinity76
Trinity76

Reputation: 665

"Uncaught SyntaxError: Unexpected token <" when trying to use content of Rails array in Javascript

In Rails 5 I want to use the content of a Rails array inside Javascript:

in my harddisk_controller.rb:

@locations = Harddisk.select(:location).distinct # grab a collection of distinct harddisk locations objects
@harddisk_locations = []
@locations.each do |location|
  @harddisk_locations << location.location # put only the location names into an array
end

I'm trying to achieve to load the content of Rails' @harddisk_locations into Javascript's harddisk_locations:

in application.js:

var harddisk_locations = [<%= raw @harddisk_locations.to_json %>];

But I'm getting the error message with highlight on [<%= raw @harddisk_locations.to_json %>] in my browser console:

Uncaught SyntaxError: Unexpected token <

I assume Javascript is complaining about the

<

right after

[

character. How to fix this?

Upvotes: 2

Views: 1460

Answers (2)

Igor Drozdov
Igor Drozdov

Reputation: 15045

The problem is that you're using invalid syntax for js. That's why you need to rename application.js to application.js.erb.

Be aware, if you want to inject a string into erb you need to use quotes:

var harddisk_locations = ["<%= somestring %>"];

In you case, I guess, raw @harddisk_locations.to_json is a valid json, so the quotes are not needed.

Upvotes: 4

Ravi Teja Dandu
Ravi Teja Dandu

Reputation: 476

You are using an ERB syntax inside a .js file. A better solution would be to create a new .js.erb file and add your required code in that file.

A suggestion regarding your code, you can replace existing code with @harddisk_locations = Harddisk.select(:location).distinct.map(&:location)

Upvotes: 2

Related Questions