There are few changes required in HTML page
- Add action to form
- change button type to submit
-
first checkbox name is changed to “colors” as per node.js code
<form method="POST" action="send">
<div>
<input type="checkbox" name="colors" value="red">red
<br>
<input type="checkbox" name='colors' value="blue">blue
<br>
<input type="checkbox" name='colors' value="Green">green
<br>
<input type="checkbox" name='colors' value="black">black
<br>
</div>
<br>
<br>
<div>
<input type="checkbox" name='cars' value="benz">Benz
<br>
<input type="checkbox" name='cars' value="BMW">BMW
<br>
<input type="checkbox" name='cars' value="Kia">Kia
<br>
<input type="checkbox" name='cars' value="Mazzerati">Mazzerati
<br>
</div>
<input type="submit" value="send">
Above code is sending POST form data that I observed on network tab. Please check end to end with your backend code.
OR
You can use jquery AJAX as well but you forgot to add “data” attribute. Note: form data will not be automatically added to ajax call.
Here’s my HTML script:
<body>
<form method="POST">
<div>
<input type="checkbox" name="color" value="red">red
<br>
<input type="checkbox" name='color' value="blue">blue
<br>
<input type="checkbox" name='color' value="Green">green
<br>
<input type="checkbox" name='color' value="black">black
<br>
</div>
<br>
<br>
<div>
<input type="checkbox" name='cars' value="benz">Benz
<br>
<input type="checkbox" name='cars' value="BMW">BMW
<br>
<input type="checkbox" name='cars' value="Kia">Kia
<br>
<input type="checkbox" name='cars' value="Mazzerati">Mazzerati
<br>
</div>
<input type="button" onclick="sendOPT()" value="send">
</form>
<div id="show"></div>
</body>
<script src="../js/jquery-3.3.1.min.js"></script>
<script>
function sendOPT() {
$.ajax({
url: '/send',
method: 'post'
}).done(message => {
$(show).html("its Done");
})
}
</script>
I want to send checked checkBox item into my backend (nodejs) and save them into my database(Mongodb)
I wrote my backend side as the following:
app.post('/send', async(req, res) => {
try {
console.log("start");
const body = _.pick(req.body, ['colors', 'cars'])
console.log(body);
let test = new fav({
favcolor: body.colors,
favcar: body.cars
})
await test.save();
console.log(test);
res.send('ok')
} catch (e) {
res.status(400).json({
ERROR: `Something wend wrong and err is ${e}.`
})
}
});
When I check and click for send, I have nothing, I have tested my database and backend by any input like as radio or text and it working good, but in this situation, not working.
[NOTE]:
- I use (express,Mongoose,body-parse,lodash,…)