0

I'm trying to authenticate through AJAX and can not figure out how to show a message when ajax request is finished. When email and password are invalid, I need to show an error message.

The code of a haml page

=form_for(resource, :as => resource_name, :url => session_path(resource_name), :remote => true, :format => :json) do |f| 
    = label :user, :email, "Email"
    = text_field :user, :email
    = label :user, :password
    = password_field :user, :password
    %input{:type => "submit", :value => "Sign in"}

and the result enter image description here

Your ideas?

2
  • We will need your UsersController/SessionsController code to answer your question. Commented Sep 16, 2012 at 13:59
  • Yes what does the controller look like? Commented Sep 16, 2012 at 14:03

1 Answer 1

3

Since you're using JSON format (only data, not actions), you need some kind of client-side processing.

Try to process response in ajax:success handler. With jQuery it can be something like:

$('#the_form_id').on('ajax:success', function(data, status, xhr) {
  if(data) {
    if(data.status) { // Login successful
      alert("Login successful");
    }
    else {
      alert(data.errors);
      // To show errors inside a DOM element
      $("#error-wrapper").html(data.errors);
    }
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

In an ajax request you have to take care of displaying your message yourself. If you have a specific container / dom element reserved for displaying the flash message, you can modifiy dimuchs answer to display the message there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.