Search code examples
ruby-on-railsajaxxmlhttprequestruby-on-rails-5actionpack

Rails 5 error: XMLHttpRequest.response is null


Given a partial view that simply turns a given ruby object into JSON, shouldn't render 'ajax/object' and render json: @object deliver the same result?

ajax/object.json.erb:

<%= @object.to_json %>

@object:

{&quot;id&quot;:1}

Because they don't.

render 'ajax/object' results in XMLHttpRequest.response === null and the rendered view being sent as: (Snippet taken from saved .har file)

      "content": {
        "size": 18,
        "mimeType": "application/json",
        "compression": -11,
        "text": "{&quot;id&quot;:1}"
      },

render json: @object, on the other hand, results in the behavior I expected: XMLHttpRequest.response === ("id": 1)

So my question is: Is this difference in rendering behavior a bug and, if not, what is the purpose of render 'ajax/object''s rendering behavior?


Solution

  • The issue here is that the string created in the template is HTML escaped.

    While you could fix it with:

    <%= raw( @object.to_json ) %>
    

    Using a template is stupid and silly in the first place. Rails has to lookup the template by traversing a tree of possible files and then has to parse ERB and create a string buffer etc. This is just ridiculously inefficient for something which can be handled by passing an object to a JSON encoder.