I have no trouble making typical AJAX calls to and from Rails(3) with JSON objects and jQuery-rails (jQuery library plus a special rails.js file).
In one controller, though, I want to RETURN some JSON in an erb template (create.js.erb) after an AJAX call.
I've tried every combination of things in the controller (@object.to_json, '[{"content":"hello world"}]', etc.) and in the template itself (JSON.parse(), single quotes, double quotes, etc.), but the object keeps on rendering like this:
'[{"groups":{},"created_at":"2010-09-21T03:49:34Z" ...
and as a result, my jQuery code cannot parse it and I get errors.
How do I need to prep my object in the controller, and what erb syntax do I need in the view for it to render as a valid JSON object?
Thanks so much!
Using
html_escape
orraw
alone will leave you vulnerable to XSS.Instead, define a sensible version of the
json_escape
(a.k.a.j
) helper:Use it like this:
See this post for further details.
Be aware that there's a naming conflict between
j
aliased tojson_escape
in ERB::Util andj
aliased toescape_javascript
in ActionView::Helpers::JavaScriptHelper. It's my hope that the JavaScriptHelper alias will be renamed tojs
.To return
json
you have to write your render in the controller as follows:and the
.to_json
will automatically be called.If you would want to include some relations, you could do the following:
I am not sure if it would work to use an erb to render your json.
I'm not sure this is the cause, but you can also try playing around with
html_safe
method. ERB might be escaping your JSON because it thinks it's not html safe. Try calling that method when using the string:Only
to_json.html_safe
is needed:Patch to make
to_json
respond tohtml_safe?
and returntrue
automatically:You can call render in your controller, but that will be a problem if you need to possibly render more than a few partials for subsequent dom insertion by the handler. I needed to set multiple html fragments into a hash, and I've been able to return erb which basically uses hash.to_json.html_safe as neutrino suggests above and allows me to render multiple partials in the process.