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?

2 Answers 2

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) %>");
Sign up to request clarification or add additional context in comments.

1 Comment

Oh yeah, that's nicer.
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.

1 Comment

Ok. I just used raw but I see that they are actually the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.