Reputation: 3
I'm currently playing around with node.js, express, and jade and can't figure out why it won't redirect when I use a jQuery POST. I read around and it seems this is a known bug but can't figure out anyway around it. Here is my code for reference:
backend code:
app.get('/ace', function (req, res) {
res.render('ace', {test: 4});
});
app.post('/ace', function (req, res) {
var input = req.body.submittedInput;
console.log(input);
res.redirect('/');
});
frontend (in jade)
script
var editor = ace.edit("editor");
var session = editor.getSession();
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
$.noConflict();
jQuery(document).ready(function($) {
// Use jQuery in here
$("#submitButton").click(function() {
$.post("/ace",
{ "submittedInput": session.getLines(0, session.getLength()-1)},
"json");
});
});
button(type='button', id="submitButton")
| SUBMIT
and here is the console output
[ '//Begin Typing Code here', '4' ]
POST /ace 302 5ms - 35
GET / 200 59ms - 12.54kb
Upvotes: 0
Views: 268
Reputation: 161457
This seems to be a misunderstanding how what exactly the code you have written does:
$.post(
"/ace",
{ "submittedInput": session.getLines(0, session.getLength()-1)},
"json"
);
This sends a POST request to /ace
, but your redirect will only effect this specific request, it does not effect the whole browser session. What you have now is essentially the same as if you removed the redirect line and instead did a second $.post
request to /
after the first request completed.
If you want to redirect the browser itself, then you would need to remove your redirect
line and instead send back some JSON containing the target URI or something. Then your jQuery code would read that code and redirect the page itself.
Upvotes: 1