Nick Nick - 3 months ago 14
Ajax Question

Update Express.js's local route variables without reloading the page

I'm using node.js with the express.js framework and EJS to handle the templates.

Here's my route:

app.get('/',function(req,res) {
res.render('index', {
matches: [],
status_message: '',
message: ''
});
});


When I call app.post, I run queries to a database updating variables
'matches'
and
'status_message'
. How would I update these variables rendered in the page without having the page reload.

For example, if the user provides invalid credentials, I'd like update the
'status_message'
to "Invalid Credentials".

Answer

Use AJAX.

Basically, modern browsers implement a class called XMLHttpRequest that can make HTTP requests to HTTP servers. In your client-side Javascript, create an XMLHttpRequest object and use it to execute the post request to your server. Use the same XMLHTTPRequest object to listen for the server response, then do whatever you want with the response, such as updating a div.

You tagged this question with ajax so I guess you already know about it, but you didn't mention or ask anything about it in your question. There are tons of examples of this kind of thing online, e.g. here that you can try. There's also jQuery.ajax() which you might find easier to use than native AJAX.

Comments