req.body is undefined with JQuery

I want to implement AJAX using express and jquery.


const increment = () => {
    let value = parseInt(document.getElementById('number').value);
    value = isNaN(value) ? 0 : value;
    document.getElementById('number').value = value;
    console.log(document.getElementById('number').value) <== returns correct number
<button type="button" onclick='increment()'>add</button>
<form action="/dash" method="POST" id="mon">
    <input id="number" name='number' value=<%=money %>>
    <button type="submit">submit</button>

index.js'/dash', isLogin, async (req, res) => {
    const num = req.body.number;
    const filter = {username: req.user.username};
    const update = {money: num};
    await User.updateOne(filter, update);
    console.log(num) <== also returns correct number

And that, when alone (without jquery), is working perfectly, it returns the right number and save it to db.

The problem arises when I add jquery code to the script.

JQuery code in index.ejs‘s script tag:

$(document).ready(function () {
        $("form#mon").on('submit', function (e) {
            var data = $('input[name=number]').val();
                type: 'post',
                url: 'dash',
                data: data,
                dataType: 'text',
                .done(function (data) {
                    var num = $('input[name=number]').val();

And basically it also works, it won’t refresh the page when the button is clicked, but now the console.log(req.body.number) in index.js returns undefined, and it won’t save in db.

Thank You for Your answers.

>Solution :

Form data consists of a series of key=value pairs.

You have:

var data = $('input[name=number]').val();

So the data you are sending is one value with no keys.

You need:

var data = {
    number: $('input[name=number]').val();

Leave a Reply