Skip to content

Instantly share code, notes, and snippets.

Created August 21, 2012 01:15
Show Gist options
  • Save linjunpop/3410235 to your computer and use it in GitHub Desktop.
Save linjunpop/3410235 to your computer and use it in GitHub Desktop.
Rails flash messages with AJAX requests
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
class ApplicationController < ActionController::Base
after_filter :flash_to_headers
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
def flash_message
[:error, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
def flash_type
[:error, :warning, :notice].each do |type|
return type unless flash[type].blank?
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
Copy link

Thanks for compiling this! It saved me a lot of time. You might be interested in this fork which fixes several bugs, including the one that caused the flash to output error if no flash messages were present.

Copy link

Here's my version of the application_controller.rb:

if request.xhr?
  #avoiding XSS injections via flash
  flash_json = Hash[{|k,v| [k,ERB::Util.h(v)] }].to_json
  response.headers['X-Flash-Messages'] = flash_json

Copy link

AHaymond commented Apr 3, 2014

do either of these actually work? I haven't had any success

Copy link

I didn't have any success either. I stripped out the above code and realized the flash was being set through the session. Maybe it will help you.

def ajax_controller_action
    if request.xhr?
      flash[:notice] = "message."
      render js: "window.location = #{your_path}"
    -if session["flash"]["flashes"]
      - session["flash"]["flashes"].each do |type, message|
          = type
          = message

Copy link

plicjo commented Aug 18, 2014

Thanks James! This just helped me out.

Copy link

Yes, Thanks James It even worked out for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment