When creating a webapp with HTML, Javascript, and Node with Express, I often want to change pages based on actions.
In HTML I can add an href link, and then have my app.js Node file route appropriately.
For example:
In Node:
app.get('/test', function(req,res){
res.render('public/webpage.html', {name: 'MyName'});
});
In HTML:
<a href="test">Bar</a>
However, I am struggling to do this through Javascript rather than with HTML. In this case, I often want to send form data through Javascript to my Node server, then let the Node server use that information to render a new page.
For example:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:8888/route',
followAllRedirects: true,
'success': function(res){
#Ideally, the webpage would be changed by the node route,
}
});
In Node:
app.post('/route', function(req,res){
res.render('public/webpage.html', {name: 'John'});
});
Currently, my HTTP request does not lead to a new page being rendered, but rather I get sent back a string which is the entire html page that I wanted to be rendered. For an easy work around I am simply doing this:
'success': function(res){
document.location.href = '/newpage.html';
$('body').replaceWith(res);
}
Is there a way for a javascript method, to call a POST request to a Node server (or any type of request where data can be sent), and then have Node render a different html page with dynamic variables? I cannot just do window.href.location since this would not render the variable inputs for the static page (these have to be calculated on the server side). Also, while I'm sure there is a way to render the pages in JS and would appreciate info on that, I am more interested in how to do it on the server since I think handling all redirects there would simply be cleaner.
Thank you!