I'm using AJAX in my app and at the frontend I have
$.post('/post', $("#submitform").serialize())
.done(function(res) {
//3. Receive the server response, no need to emit an event
if (res.success) {
//4. Show the updated text
console.log('success');
}
else {
alert(res.error);
}})
.fail(function(res) {
alert("Server Error: " + res.status + " " + res.statusText);
});
return false;
});
I'm sending back from my Node.Js/Express app route:
res.send(statement);
However, res.success
doesn't get triggered and instead I go into alert(res.error)
although the process performs fine at the backend.
What am I doing wrong? Shall I send something else from the backend of my app, like res.success
?
Thank you!
Since, you are using ExpressJS with NodeJS on your server, you can send a error status code with the server when the HTTP request is not correct:
res.status(400).send('Bad Request')
In your client script which use the jQuery Deferred Object:
deferred.done()
is triggered when your HTTP request is a success;deferred.fail()
is triggered if there is a client or server error;So you should use as your code:
$.post('/post', $("#submitform").serialize())
.done(function(res) {
// Receive the successful server response
console.log('success');
})
.fail(function(res) {
// Receive the error server response
alert("Error: " + res.status + " " + res.statusText);
});