Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
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
@briarsweetbriar
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.

@toadkicker
Copy link

Here's my version of the application_controller.rb:

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

@AHaymond
Copy link

AHaymond commented Apr 3, 2014

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

@JamesDullaghan
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."
      flash.keep(:notice)
      render js: "window.location = #{your_path}"
    end
end
    -if session["flash"]["flashes"]
      - session["flash"]["flashes"].each do |type, message|
          = type
          = message

@plicjo
Copy link

plicjo commented Aug 18, 2014

Thanks James! This just helped me out.

@yash-m-agarwal
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