Reputation: 678
I am sending a post request to server via ajax:
result.ejs
$.ajax({
type: "POST",
url: "/result",
data: { score: score, rank: rank, name: name, email: email, historyLog: historyLog }
});
I am reciveing it and saving data to the database:
resultController.js
app.post('/result', urlencodedParser, function(req, res) {
var user = new User({
name: req.body.name,
email: req.body.email,
score: req.body.score,
rank: req.body.rank,
historyLog: req.body.historyLog
});
user.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
});
});
After saving it I want to render a new view, and I can't get it working. I have tried adding this after the save function:
res.redirect('page')
, res.render('page')
, setting headers html/text
None of the above is working. Any suggestions?
Upvotes: 0
Views: 7700
Reputation: 11
This is working fine to post. Better use form to post.
app.post('/result', function(req, res) {
new user({
name: req.body.name,
email: req.body.email,
score: req.body.score,
rank: req.body.rank,
historyLog: req.body.historyLog
}).save(function(err,doc) {
if (err) throw err;
else { res.render('pagename.ejs'); }
console.log('User saved successfully!',doc);
}); });
hope this will help you.
Upvotes: 1
Reputation: 1345
If you want to render page after saving - add it in saving callback, like this
app.post('/result', urlencodedParser, function(req, res) {
var user = new User({
name: req.body.name,
email: req.body.email,
score: req.body.score,
rank: req.body.rank,
historyLog: req.body.historyLog
});
user.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
res.render('page');//ADD HERE redirect o render
});
});
Upvotes: -1
Reputation:
AJAX is usually used precisely when you don't want to navigate elsewhere, but talk to the server in the background instead. To still do it your way, use res.send("done");
inside the save callback, right after console.log('User saved successfully!);
, then add this to your ajax request:
success: function () { window.location.href = "/page"; }
A much simpler way to implement the entire process is to use a <form method="post" action="/result">
and submit it.
Upvotes: 3