I am trying to receive login fail events on a devise AJAX login form. I have overriden the devise sessions controller like so:
class SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(:scope => resource_name, :recall => '#{controller_path}#failure')
sign_in_and_redirect(resource_name, resource)
end
def sign_in_and_redirect(resource_or_scope, resource=nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
resource ||= resource_or_scope
sign_in(scope, resource) unless warden.user(scope) == resource
return render :json => {:success => true}
end
def failure
return render :json => {:success => false, :errors => ["Login failed."]}
end
end
the json on failure never actually triggers on a 401 unauthorised response. The js on sign_in_and_redirect works fine though.
Here is the section of my js where i expect an alert to show:
$(document).on('click', '#login-btn', function(){
$("#login-modal").toggleClass("is-active");
$("form#login_user_form").bind("ajax:success", function(e, data, status, xhr) {
if (data.success) {
$("#login-modal").toggleClass("is-active");
} else {
return alert('failure!'); // this never happens
}
});
});
EDIT - So I managed to get the desired behaviour by checking for data.status == 200
instead of data.success
... I am still wondering if this is the right way to go about it or if I'm missing something
It could be that your ajax is not firing your success
at all. So try handling the other ajax events and inspecting the result to help you debug if you haven't done so already:
$(document).on('click', '#login-btn', function() {
$("#login-modal").toggleClass("is-active");
$("form#login_user_form").bind("ajax:success", function(e, data, status, xhr) {
if (data.success) {
$("#login-modal").toggleClass("is-active");
} else {
return alert('failure!');
}
}).bind("ajax:complete", function(e, xhr, status, error) { // <----
return alert(xhr);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With