Rails escape_javascript and remotipart


When replacing html with jquery and rails (tested on 4.0.4) the following works:

Content of replace.js.erb

$('#my_div').html("<%= j(render 'my_partial') %>");

Content of _my_partial.html.erb

"This" works
<%= '"This" also works' %>

However it fails when replace.js.erb is rendered in reponse to a ajax file submit using the remotipart gem (1.2.1) as shown below.

Content of create.html.erb

<%= form_for @my_model, :html => {:remote => true} do |f| %>
  <%= f.file_field :some_file %>
  <%= f.submit %>
<% end %>

It causes the following javascript error in the browser because quotes aren't escaped correctly.

SyntaxError: Unexpected identifier

Server response: $('#my_div').html("\"This\" works\n"This" fails\n");

Note that if I submit without selecting a file the javascript error does not occur and it re-renders correctly. It looks like remotipart isn't invoked when a file isn't selected, probably because a multipart form isn't required.

Try as below

$("#my_div").html("<%= escape_javascript(render :partial => 'my_partial') %>");
By : Dave

I finally got to fix the same issue trying something like:

$("#my_div").html("<%= escape_javascript(render :partial => 'my_partial').gsub('&quot;', "'") %>");
By : Moh

This video can help you solving your question :)
By: admin