I have a node.js application with a connection to a remote mongoDB server. The database contains some custom codes that have been pre-created and distributed to certain users. The idea is that only those who enter one of such codes into a form on the index page can be allowed to view the rest of the site. That is, I want to cross-reference the code entered with the master list stored in my database.
This is an example of what I'm trying to do(note this is in routes/index.js):
collection.findOne({ "Code": "fooCode" }, function(err, doc){
if you cannot find fooCode
show an error message, clear the input area and tell the user to re-enter a correct code
if you find fooCode
redirect to a new page;
});
The above code is within a router.post('/', function(req, res){...}) function.
My question is, how do I clear the text input area(without refreshing the page) and ask the user to re-enter a new code when a wrong code is entered?
Secondly how do I redirect the user to a new page on valid entry of a code? Thanks.
For that kind of behavior you would need to submit the form via XHR, parse the (JSON) response, and then clear the form on error and display error information. On the server side you can simply do something like res.json({ status: 'success' }); or res.json({ status: 'error', error: 'Bad token' });
On success, you could do the redirect in the browser via window.location.replace("http://example.org/foo"); or if you want the current page in the session history (e.g. reachable with the browser's back button) you can use window.location.href = "http://example.org/foo".