Skip to content

Instantly share code, notes, and snippets.

@mebezac
Created February 11, 2014 21:06
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mebezac/8944150 to your computer and use it in GitHub Desktop.
Save mebezac/8944150 to your computer and use it in GitHub Desktop.
Rails Ajax Flash Messages
<div id="main" role="main">
<div class="container">
<div class="row">
<div class="span12" id="top-div"> <!--! added "top-div" id to help with ajax -->
<%= render 'layouts/messages' %>
<%= yield %>
</div>
</div>
<footer>
</footer>
</div> <!--! end of .container -->
</div> <!--! end of #main -->
def ajax_flash(div_id)
response = ""
flash_div = ""
flash.each do |name, msg|
if msg.is_a?(String)
flash_div = "<div class=\"alert alert-#{name == :notice ? 'success' : 'error'} ajax_flash\"><a class=\"close\" data-dismiss=\"alert\">&#215;</a> <div id=\"flash_#{name == :notice ? 'notice' : 'error'}\">#{h(msg)}</div> </div>"
end
end
response = "$('.ajax_flash').remove();$('#{div_id}').prepend('#{flash_div}');"
response.html_safe
end
def vote
vote = Vote.create(voteable: @post, creator: current_user, vote: params[:vote])
respond_to do |format|
format.html do
if vote.valid?
flash[:notice] = "Your vote was counted"
else
flash[:error] = "You can not vote on \"#{@post.title}\" more than once."
end
redirect_to :back
end
format.js do
if vote.valid?
flash.now[:notice] = "Your vote was counted"
else
flash.now[:error] = "You can't vote on that more than once"
end
end
end
end
$("#post_<%= @post.id %>_votes").html("<%= @post.total_votes %>");
<%= ajax_flash('#top-div') %>
@letladi
Copy link

letladi commented Aug 18, 2016

This is cool.

@handofthecode
Copy link

handofthecode commented Feb 2, 2018

Great job on this! I made just one small change so that old non-ajax notifications will also be removed from the notification bar when calling ajax_flash. https://gist.github.com/handofthecode/f3cd43c77c826a5f8d4071969a2c9708

@jsiny
Copy link

jsiny commented Apr 5, 2020

This is great, thanks for sharing!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment