Arif Arif - 1 year ago 217
Javascript Question

JSON: Uncaught SyntaxError: missing ) after argument list

In a rails app I have an object defined in a controller containing an icon and some values:

@data = "<i class='fa fa-circle fa-lg'></i><span>Speed: </span> #{b.speed.to_f} | Time: #{b.gps_date.try(:strftime, '%-m/%e %H:%M')}} <br />".html_safe.to_json

In view I parse it like this:

var data = JSON.parse('<%= raw @data.as_json %>');

But I get the following error:

Uncaught SyntaxError: missing ) after argument list

I works fine when I remove the icon code that contains the single quotes for class

<i class='fa fa-circle fa-lg'></i>

How can I fix this error?

Answer Source

You want to send the HTML string to JS so need of to_json, as this is used to convert Hash to JSON . So just use html_safe in server side.

And in client side, since you have the all HTML in string no need of as_json, just use the string as you would normally do in JS. as_json is a method used as ActiveRecord Serializer.

@data = "<i class='fa fa-circle fa-lg'></i><span>Speed: </span> #{b.speed.to_f} | Time: #{b.gps_date.try(:strftime, '%-m/%e %H:%M')}} <br />".html_safe


var data = <%= raw @data %>;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download