Rails flash messages with AJAX requests
-
-
Save briarsweetbriar/5506787 to your computer and use it in GitHub Desktop.
This file contains 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
#flash-message | |
- flash.each do |name, msg| | |
= content_tag :div, msg, :id => "flash_#{name}" |
This file contains 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
class ApplicationController < ActionController::Base | |
protect_from_forgery | |
after_filter :flash_to_headers | |
private | |
def flash_to_headers | |
return unless request.xhr? | |
response.headers['X-Message'] = flash_message | |
response.headers["X-Message-Type"] = flash_type.to_s | |
# Prevents flash from appearing after page reload. | |
# Side-effect: flash won't appear after a redirect. | |
# Comment-out if you use redirects. | |
flash.discard | |
end | |
def flash_message | |
[:error, :warning, :notice].each do |type| | |
return flash[type] unless flash[type].blank? | |
end | |
return '' | |
end | |
def flash_type | |
[:error, :warning, :notice].each do |type| | |
return type unless flash[type].blank? | |
end | |
end | |
end |
This file contains 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
show_ajax_message = (msg, type) -> | |
$("#flash-message").html "<div id='flash-#{type}'>#{msg}</div>" | |
$("#flash-#{type}").delay(5000).slideUp 'slow' | |
$(document).ajaxComplete (event, request) -> | |
msg = request.getResponseHeader("X-Message") | |
type = request.getResponseHeader("X-Message-Type") | |
show_ajax_message msg, type if msg? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, it worked perfectly. Is there a way to handle both redirects and well as reload of page?