Title: AJAX success:function always returning success (and 200 status code), error function not triggering
Tags: javascript;jquery;html;ajax
Question: I'm a bit of a beginner when it comes to AJAX calls so apologies in advance because I'm stuck and I have no idea why!
In summary, I have my own server which is displaying a log in page. Using a router I am determining whether or not the details entered in the form are correct for the user to proceed to the homepage. My log in button is also linked to AJAX whereby I add an event handler which for now [should] displays alert boxes based on the outcome of the check in the router.
So.. my problem is displaying the correct alert boxes for each response. The 'success' alert box is always displaying as is the status code of 200. The code for error:function is not even being reached.
I have a router file to serve the pages and deal with the log in check, a js file containing the correct combinations of log in credentials, a login html page and a login js file. I am using javascript and AJAX and google chrome for debugging. Some of the code I think you will need for the question is below. Please ask if you require any more.
Login check on router:
app.post('/api/login/', function (req, res) {
console.log(req.body);
var emailLog = req.body.email;
var passwordLog = req.body.password;
validUser = false;
// Search user data
for (var x in USERS.users) {
if (emailLog === USERS.users[x].email &amp;&amp; passwordLog === USERS.users[x].password) {
validUser = true;
break;
}
}
if (validUser === true) {
console.log("Log in successful");
res.send('Success');
} else {
console.log("Incorrect combination");
res.send('Error');
}
});
Login.js
This file is carrying out the AJAX stuff:
$(document).ready(function(){
console.log("in doc ready");
$("#submit_button").click(function(e){
console.log("in event handler");
e.preventDefault();
$.ajax({type: "POST",
url: "/api/login",
data: { email: $("#email").val(),password: $("#password").val() },
success:function(data, textStatus, xhr){
alert("Successful");
console.log(xhr.status);
console.log(data);
},
error:function(data){
alert("Unsuccessful");
//$("#errorMessage").html("Incorrect email or password - Try again");
}
});
Help! I've looked through several pages of AJAX questions on here and none of them have worked for me.. Ultimately I would like to add error text to a div on the log in page, but for now I will be happy with just displaying the correct alert!!! ... Why is it always returning the success alert box even if I type in an incorrect combination? Any suggestions or pointers for the right direction for fixing this error?
Update
This is what shows in the console from developer tools for both a correct combination and an incorrect combination:
login.js:2 in doc ready
login.js:5 in event handler
login.js:18 200
login.js:20 Success
login.js:5 in event handler
login.js:18 200
login.js:20 Error
And this is in the cmd window:
Example app listening at http://75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0:3000
{ email: 'ashleyherrera@example.net', password: 'a' }
ashleyherrera@example.net
Valid user : true
Log in successful
{ email: 'ashleyherrera@example.net', password: 't' }
ashleyherrera@example.net
Valid user : false
Incorrect log in combination - re-directing back to login page

Here is the accepted answer: In Terms of AJAX, as long as a status "200" is returned, this is regarded as "success" and the error function will not fire. It has nothing to do with what you send as response, it's only the http status code.
so adjust your success function:
success:function(data, textStatus, xhr){
console.log(xhr.status);
console.log(data);
if ( data == "Success" ) // thats what you send in case of a proper login
alert("Successful")
},
Comment for this answer: Thank you for that clarification. I did not read that in the ajax documentation... I must've skipped over it without realizing! I've added that in and it works! For adding an error alert box do I need to use error:function() or could I simply use an else statement on top of that if?

Here is another answer: Put a breakpoint at this line and make sure it turns out ok
if (emailLog === USERS.users[x].email &amp;&amp; passwordLog === USERS.users[x].password) {
validUser = true;
break;
}
This logic is always making the validuser true which is always making it a success.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:04/29/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><jquery><html><ajax>', 'Title': 'AJAX success:function always returning success (and 200 status code), error function not triggering', 'ViewCount': 1468, 'id': 29945726, 'user_AboutMe': '', 'user_AccountId': 3889455.0, 'user_DisplayName': 'hturner', 'user_Reputation': 195.0, 'user_Views': 19.0, 'user_id': 3220059.0}}