Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails flash messages with AJAX requests & twitter-bootstrap
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- flash_message.js.coffee expects to find a div with this id in your html code -->
<div id="flash_hook"></div>
</body>
</html>
# encoding: UTF-8
class ApplicationController < ActionController::Base
protect_from_forgery
after_filter :flash_to_headers
private
def flash_to_headers
return unless request.xhr?
msg = flash_message
#replace german umlaute encoded in utf-8 to html escaped ones
msg = msg.gsub("ä","&auml;").gsub("ü","&uuml;").gsub("ö","&ouml;").gsub("Ä","&Auml;").gsub("Ü","&Uuml;").gsub("Ö","&Ouml;").gsub("ß","&szlig;")
response.headers['X-Message'] = msg
response.headers["X-Message-Type"] = flash_type.to_s
flash.discard # don't want the flash to appear when you reload page
end
def flash_message
[:error, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
end
# if we don't return something here, the above code will return "error, warning, notice"
return ''
end
def flash_type
#:keep will instruct the js to not update or remove the shown message.
#just write flash[:keep] = true (or any other value) in your controller code
[:error, :warning, :notice, :keep].each do |type|
return type unless flash[type].blank?
end
#don't return the array from above which would happen if we don't have an explicit return statement
#returning :empty will also allow you to easily know that no flash message was transmitted
return :empty
end
end
#ajax call to show flash messages when they are transmitted in the header
#this code assumes the following
# 1) you're using twitter-bootstrap 2.3 (although it will work if you don't)
# 2) you've got a div with the id flash_hook somewhere in your html code
$(document).ajaxComplete (event, request) ->
msg = request.getResponseHeader("X-Message")
alert_type = 'alert-success'
alert_type = 'alert-error' unless request.getResponseHeader("X-Message-Type").indexOf("error") is -1
unless request.getResponseHeader("X-Message-Type").indexOf("keep") is 0
#add flash message if there is any text to display
$("#flash_hook").replaceWith("<div id='flash_hook'>
<p>&nbsp;</p>
<div class='row'>
<div class='span10 offset1'>
<div class='alert " + alert_type + "'>
<button type='button' class='close' data-dismiss='alert'>&times;</button>
" + msg + "
</div>
</div>
</div>
</div>") if msg
#delete the flash message (if it was there before) when an ajax request returns no flash message
$("#flash_hook").replaceWith("<div id='flash_hook'></div>") unless msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.