I’m trying to redirect to a specified page after post via jQuery. Here’s my POST code:
$.post("/addcompany", {
name: $('#company_name').val(),
phone: $('#company_phone').val(),
email: $('#company_email').val(),
suppliers: JSON.stringify(suppliers),
}, function(){
alert('after post');
window.location.href = '/companies';
}
);
This is my backend code on NodeJS:
app.post('/addcompany',function(req,res){
db.collection("companies",function(err,collection){
collection.insert( {
"name":req.body.name,
"email":req.body.email,
"phone":req.body.phone,
"suppliers" : JSON.parse(req.body.suppliers)
});
});
res.redirect('/companies');
});
The problem is if I don’r redirect to ‘/companies’ both in jQuery script and in NodeJS-backend code, my redirection doesn’t work. Where should I place my redirection code? Is it normal, that I have to place it twice – both on server and on client? Thanks!
You should only redirect in this situation on the frontend. To achieve that properly I think you should have
res.send()on the backend (empty 200 response, to let the client know everything went ok on the server side).If you want to redirect on the server side than you shouldn’t use Ajax, just plain old post request.