Reputation: 55
I'm Making a simple voting system using ajax.
here's the code...
// Receving The Votes
app.post('/submitvote', (req, res) => {
// req.body, body is undefined
// should be: { choice: 2 }, 2 is just an example
console.log(req.body);
});
This code saves vote from the judge's into a variable just for testing. But The body(where the choice is) is undefined
let's look at the client side...
var picked = 0
function voteto(plr) {
+plr;
picked = plr;
console.log(`Picked Player #${plr}`)
if (plr == 1) {
document.getElementById('plr1').style.backgroundColor = 'blue';
} else {
document.getElementById('plr1').style.backgroundColor = 'darkblue';
}
if (plr == 2) {
document.getElementById('plr2').style.backgroundColor = 'blue';
} else {
document.getElementById('plr2').style.backgroundColor = 'darkblue';
}
if (plr == 3) {
document.getElementById('plr3').style.backgroundColor = 'blue';
} else {
document.getElementById('plr3').style.backgroundColor = 'darkblue';
}
}
$(document).ready(function(){
$("#submit").click(function(){
console.log("Sending Data");
$.post("/submitvote", {
choice: picked,
});
});
});
The voteto
function is a selector for the vote.
I just send the picked
variable in the choice
parameter(I don't know what would you call that). I didn't make a callback since it's just saving it.
But The Thing Is The Body is undefined. Why?
Upvotes: 0
Views: 37
Reputation: 55
Add app.use(express.urlencoded())
in the app.js(entry). This Works For Me!
Upvotes: 0