Created
March 11, 2011 18:06
-
-
Save kurbmedia/866286 to your computer and use it in GitHub Desktop.
Adds flash messages to the response header so they can be picked up via js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
after_filter :add_flash_messages | |
# Adds flash messages to the HTTP headers so they can be used on the current request with AJAX | |
def add_flash_messages | |
return true unless response.content_type.to_s.match(/javascript/i) | |
return true if flash.keys.empty? | |
response.headers['X-Flash-Messages'] = flash.to_json | |
flash.discard | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Event trigger for jquery that collects the flash messages from the header. Simply bind something to the "flash:add" event. | |
$(document).ajaxSuccess(add_flash_messages); | |
function add_flash_messages(event, xhr, settings){ | |
var messages = xhr.getResponseHeader('X-Flash-Messages'), divs = []; | |
if(!messages) return true; | |
messages = $.parseJSON(messages); | |
$.each(messages, function(key, value){ | |
var div = $("<div></div>").addClass('flash_message') | |
.addClass('flash_'+key) | |
.addClass(key) | |
.hide() | |
.html(value+"<span>X</span>"); | |
$.event.trigger('flash:add', [div]); | |
}); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment