0

I've got a javascript view (add_to_garden.js.erb) that responds to an ajax action and tries to render a flash message telling the user about the updated info. This works:

// Flash message to user
<% flash.each do |key, message| %>
  $("#flash").html("<%= j(render( partial: "shared/flash_message", locals: {key: key, message: message } )) %>");
<% end %>

Of course as it's written above, the html for each flash message will replace the previous one so only the last message will be shown to the user.

This does render all the messages...

// Flash message to user
<% flash[:error] = "AAAAHHHHHH... an error" %>
<% flash[:info] = "Just so you know, that was an error." %>
<% flash.each do |key, message| %>
  <% (@alerts ||= '') << render( partial: "shared/flash_message", locals: {key: key, message: message } ) %>
<% end %>
$("#flash").html("<%= j(@alerts) %>");
flashMessageSetTimeout();

...but the messages in @alerts are htmlencoded by the time they get to the browser:

chrome inspector of htmlencoded javascript response

How to fix?

doub1ejack
  • 10,627
  • 20
  • 66
  • 125

2 Answers2

1

Use append:

<% flash.each do |key, message| %>
  $("#flash").append("<%= j(render( partial: "shared/flash_message", locals: {key: key, message: message } )) %>");
<% end %>

append inserts string to designated dom element.

However, if you still want to go ahead with your current approach with html() then use html_safe method:

$("#flash").html("<%= j(@alerts.html_safe) %>");
Surya
  • 15,703
  • 3
  • 51
  • 74
0

You want you use html_escape() or simply h() in rails. If you apply this to @alerts it will show the html that you want to display.

Kielstra
  • 510
  • 1
  • 3
  • 15
  • Ok. I just used `raw` but I see that [they are actually the same thing](http://stackoverflow.com/questions/4251284#39706146). – doub1ejack Jan 05 '17 at 13:07