Skip to content

Instantly share code, notes, and snippets.

@AndrewRussellHayes
Forked from linjunpop/README.md
Last active March 22, 2016 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRussellHayes/8ce421e6c81108626b71 to your computer and use it in GitHub Desktop.
Save AndrewRussellHayes/8ce421e6c81108626b71 to your computer and use it in GitHub Desktop.
Rails flash messages with AJAX requests
#flash-message
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
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
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
end
def flash_type
[:error, :warning, :notice].each do |type|
return type unless flash[type].blank?
end
end
end
var show_ajax_message;
show_ajax_message = function(msg, type) {
$("#flash-message").html("<div id='flash-" + type + "'>" + msg + "</div>");
return $("#flash-" + type).delay(5000).slideUp('slow');
};
$(document).ajaxComplete(function(event, request) {
var msg, type;
msg = request.getResponseHeader("X-Message");
type = request.getResponseHeader("X-Message-Type");
return show_ajax_message(msg, type);
});
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 #use whatever popup, notification or whatever plugin you want
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment