Ajax
First of all, I need to explain that you can't pass standard flash
functionality through the "standard" Ajax flow. Reason being that as the flash
is set in a session cookie
, you will only be able to access these with a browser refresh:
The flash is a special part of the session which is cleared with each
request. This means that values stored there will only be available in
the next request, which is useful for passing error messages etc.
You need to enure that when you send / receive ajax, in order to set the flash
messages, you'll have to cater for them in a different way; either through the ajax
call itself, or through another method.
--
Headers
Admittedly, I've never done this before, but looking at this answer suggests you can set the headers in your ajax call:
#app/controllers/your_controller.rb
class YourController < ApplicationController
after_action :flash_headers
def flash_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
private
def flash_message
[:error, :warning, :notice, nil].each do |type|
return "" if type.nil?
return flash[type] unless flash[type].blank?
end
end
def flash_type
[:error, :warning, :notice, nil].each do |type|
return "" if type.nil?
return type unless flash[type].blank?
end
end
end
I lifted that code from this answer: How do you handle Rail's flash with Ajax requests?
This sets the headers of your request, allowing you to pull this data through your JS:
#app/assets/javascripts/application.js.coffee
$(document).on "click", "a", ->
$.ajax
type: "POST",
url: path,
data: response1,
contentType: "application/json",
success: (data) ->
msg = request.getResponseHeader('X-Message')
type = request.getResponseHeader('X-Message-Type')
alert msg #should alert the flash message
If this works, it will give you the capacity to set & show the flash
messages as you wish