Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 211
Pierre Pretorius Avatar asked Dec 05 '25 14:12

Pierre Pretorius


1 Answers

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

$("#my_div").html("<%= escape_javascript(render :partial => 'my_partial').gsub('&quot;', "'") %>");
like image 97
Moh Avatar answered Dec 08 '25 10:12

Moh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!