quotation havoc while posting data in html attribute

1.2k Views Asked by At

I want to post some data as an html attribute. Suppose there is a rails variable

@fields = [{:name => "id", :type => :integer}]

I want to post in the page for use with jquery's .data(). So in the .html.erb I have

<%= form_tag( {:action => 'whatever'}, {... , :"data-fields" => h(@fields.to_json)}) %>

But while rendering, the quotations in string [{"name":"id","type":"integer"}] mess up the other attributes because Rails form_tag uses double quotes to enclose the whole json string in double quotes. How do I post json with strings as an attribute from Rails?

5

There are 5 best solutions below

1
On

Have you tried the following?

<%= form_tag { :action => "whatever" }, { :data => { :fields => h(@fields.to_json) } } %>
3
On

Here is how I side-stepped the problem:

In the form tag, I did :"data-fields" => @fields.to_json.gsub('"',"'").

This produces HTML of this sort:

"data-fields"="[{'name':'id','type':'integer'}]"

And then, in the JS, I retrieve it like this:

$.parseJSON($('form').data('fields').replace(/'/g,'"'))
0
On

Have you tried escape_javascript ? Although it has known downsides, it is not exactly for escaping JSON, and I am not sure escaped quotes will work in HTML attributes.

1
On

There is an episode on railscasts addressing your situation using a serializer. The point is that the serializer replaces double quotes with $quot; The serialuzer also gives you the ability to select which attributes to serialize and include associations.

1
On

After some trial and error this is what works.

Server side:

<% @fields = [{:name => "id", :type => :integer}] %>
<%= form_tag( '/posts/new', {id:'example',:data => { :fields=>@fields}}) %>

Generated HTML:

<form accept-charset="UTF-8" action="/posts/new" data-fields="[{&quot;name&quot;:&quot;id&quot;,&quot;type&quot;:&quot;integer&quot;}]" id="example" method="post">

Javascript wiht JQuery's data method

fields = $('#example').attr('data-fields')

I'm using rails 2.3.8 and jquery-rails 2.2.1