1

I passed a ruby variable to javascript using the to_json method, but the console returns me an error saying "SyntaxError: illegal character" for the following line:

var home = #{@home.to_json};

Does anyone knows whats wrong?

Miguel Corti
  • 372
  • 3
  • 16

1 Answers1

1

If this is in a .erb file you can do the following:

var home = <%= @home.to_json %>;

Otherwise (haml or something else) you could use the parseJSON method from jQuery in combination with Ruby's string interpolation:

var home = $.parseJSON("#{@home.to_json}");

More information about the parseJSON method can be found here.

Kevin
  • 1,213
  • 10
  • 13
  • Yeah, that was the problem, I was using based on haml. But now I have a SyntaxError: invalid property id, on the same line, for some reason it converts the line like this: `{"name":"Minas Gerais", [etc.] ` And when I set the variable directly with javascript, it works: `{"name": "Minas Gerais", [etc.] ` – Miguel Corti May 15 '15 at 19:48
  • 2
    You could try to use `html_safe`, so `@home.to_json.html_safe`. You might not even need to use `parseJSON` when using that. I'll update my answer if that works for you. – Kevin May 15 '15 at 23:32