Show flash message after form submit with ajax

I am creating my first app using rails and also im trying to add some ajax functionality to it. I have a registration form in my root url to create users, but I cannot find a way to show my success message after the user has been created. I can see the json response correctly, but not the flash message. Is there something missing in my code?

# Controller

def create
  @user = User.new(user_params(CREATE_PARAMS))

  respond_to do |format|
    if @user.save
      @user.send_activation_email
      format.html { flash[:info] = "Success!!"
                    redirect_to root_url
      }
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# application.html.erb

<body>
  <div class="container">
    <div class="message-notification">
      <%= render 'shared/alert_messages' %>
    </div>
    <%= yield %>
  </div>
</body>

# shared/_alert_messages.html.erb

<% flash.each do |message_type, message| %>
  <%= content_tag(:div, message, class: "alert-message alert-message-#    {message_type}") %>
<% end %>

# Handling errors users.coffee
$(document).on "ajax:error", "form#new_user", (event, data, status, xhr) ->
  $("form#new_user").render_form_errors "user", data.responseJSON

$.fn.render_form_errors = (model_name, errors) ->
  form = this
  this.clear_form_errors()

  $.each errors, (field, messages) ->
    input = $('input[name="' + model_name + '[' + field + ']"]');
    input.closest(".form-group").addClass("has-error")
    input.parents(".form-group").append('<span class="help-block">'  + 
      $.map(messages, (m) -> m.charAt(0).toUpperCase() + 
      m.slice(1)).join("<br />") + "</span>")

$.fn.clear_form_errors = () ->
  this.find(".form-group").removeClass("has-error")
  this.find("span.help-block").remove()

      

+3


source to share


1 answer


I think you should put flash [: info] in json block like

format.json { flash[:info] = "Success!!" }

      



instead of putting it in. html

0


source







All Articles