Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Rails flash messages with AJAX requests & twitter-bootstrap
<!DOCTYPE html>
<!-- expects to find a div with this id in your html code -->
<div id="flash_hook"></div>
# encoding: UTF-8
class ApplicationController < ActionController::Base
after_filter :flash_to_headers
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
def flash_message
[:error, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
# if we don't return something here, the above code will return "error, warning, notice"
return ''
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?
#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
#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'>
<div class='row'>
<div class='span10 offset1'>
<div class='alert " + alert_type + "'>
<button type='button' class='close' data-dismiss='alert'>&times;</button>
" + msg + "
</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