Q:

Rails: How to print error message with Ajax Jquery?

Currently, this is the code I have for creating a new message:
  if @message.save
    respond_to do |format|
      format.html { redirect_to messages_path }
      format.js
    end
  else
    flash[:notice] = "Message cannot be blank!"
    redirect_to :back
  end

How do I get the same message to print in Ajax? Would also like control to format it and position it.

A:

In aplication controller
  after_filter :add_flash_to_header

  def add_flash_to_header
    # only run this in case it's an Ajax request.
    return unless request.xhr?

    # add different flashes to header
    response.headers['X-Flash-Error'] = flash[:error] unless flash[:error].blank?
    response.headers['X-Flash-Warning'] = flash[:warning] unless flash[:warning].blank?
    response.headers['X-Flash-Notice'] = flash[:notice] unless flash[:notice].blank?
    response.headers['X-Flash-Message'] = flash[:message] unless flash[:message].blank?

    # make sure flash does not appear on the next page
    flash.discard
  end

Move notifications code into partial:
<div class="noticesWrapper">
  <% flash.each do |name, msg| %>
    <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
      <a class="close" data-dismiss="alert"><i class="icon-remove"></i></a>
      <%= msg %>
    </div>
  <% end %>
</div>

In js.erb file:
$('.noticesWrapper').html("<%= j(render partial: 'layouts/flash_notices') %>");
In controller action you need to flash messages with flash.now:
flash.now[:error] = "your message"

