I am developing in Craft 3 and the accepted answer needs some modification to work. I might also be ahead a version of jQuery. Craft 3 looks for the 'Accept' header in the controller to determine if a JSON response is needed. Therefore you need to also send an 'Accept','application/json; charset=utf-8' header to elicit a JSON response from the login command.
$('#main-nav-login').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
$.ajax({
method: 'POST',
url: '/',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept':'application/json; charset=utf-8'
}
})
.done(function (data) {
console.log(data);
// example error
// {errorCode: "invalid_credentials", error: "Invalid username or password."}
if(typeof data.error !== "undefined"){
// handle error here
console.log(`Something's not right. ${data.error}`);
}
// handle success redirect
if(typeof data.success !== "undefined" && data.success === true){
typeof data.returnUrl !== "undefined" ? location.href = data.returnUrl : location.href = '/';
}
})
.fail(function (data) {
console.log('error', data);
});
});
If the user login has failed, you will get a JSON response from the .done method that looks something like this:
{errorCode: "invalid_credentials", error: "Invalid username or password."}
You can then use this to display error messages appropriately. A successful sign in will return JSON like this:
{success: true, returnUrl: "http://localhost/", csrfTokenValue: "Q5c..."}
The returnUrl field could be used to navigate to the appropriate page.