In my application I have a login using ajax that returns a JSON result.
If it’s a success then it will return as:
{"authenticated":true,"redirect":"/posts/new"}
If it’s a fail then:
{"authenticated":false,"error":"Username or password is incorrect"}
What I want to do is inside my ajax Success callback is check what authentication is and if it’s true then do one thing and if it’s false then do another:
success: function (responseHtml)
{
if(SUCCESS IS TRUE)
{
window.location.href('REDIRECT');
}
else
{
alert('ERROR MESSAGE');
}
console.log(responseHtml);
}
Can anyone help me? I have had a look at the getJSON stuff but not sure how to use it here. Thanks
UPDATE: full code
$('form').live('submit', function (event) {
var form = $(this);
event.preventDefault();
var data = form.serialize();
$('<div id="loading">Loading...</div>').appendTo('#li-submit').hide();
$('#loading').fadeIn();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (response)
{
$('#loading').fadeOut(function() { $(this).remove(); });
if(response.authenticated)
{
window.location.href('url');
}
else
{
alert(response.error);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#loading').fadeOut(function() { $(this).remove(); });
alert('Error!');
}
});
});
You should make sure that the ‘dataType’ attribute of your AJAX config object is set to “json” or not set (it will default to auto-detect).