I am registering a user and after successful registration I want alert something in client side. So, what I do in server side, after registration I'm sending a value "registered" then when it gets that value, my client side would know that user is registred but I don't know how to get that value in my client side.
router.post('/registration', function (req, res, next) {
var stud = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
admin: 0
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(stud, function (err, result) {
assert.equal(null, err);
console.log('Student inserted');
db.close();
res.json('registred');
})
})
});
My client side code
$('.MyForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '/registration',
method: 'post',
success: function(response){
}
})
});
There is not very much because I don't know what to do next
All you still need to do is put the alert in the callback to the ajax request
success: function(response) {
alert('User registration succeeded!')
}
Since you're using HTTP protocol, why not use its cohesive response codes to indicate which action has happened? For example:
200 - user successfully created 400 - malformed input data 409 - one of unique user's model field has been already taken
And so on. Use method 'status' on response object to set appropriate return code. I assume that you are trying to create server with REST's rules in mind, therefore your endpoint should return freshly created entity on POST request.
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(stud, function (err, result) {
if(err) {
/* At this point, you may decide to check what error has been returned to decide which code will be returned*/
return res.status(400).json(err);
}
console.log('Student inserted');
db.close();
res.status(200).json(result);
})
})
On client side, code might be much more pleasant to eye after you would refactor it to use jQuery's ( since ver. 1.5.1 )'Promise API'
$.ajax({
url: 'http://localhost:8000',
method: 'POST'
})
.done(function( data ) {
})
.fail(function (reason) {
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.