Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

req.body is undefined with JQuery

I want to implement AJAX using express and jquery.

index.ejs

<script>
const increment = () => {
    let value = parseInt(document.getElementById('number').value);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
    console.log(document.getElementById('number').value) <== returns correct number
}
</script>
<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>
</form>

index.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

router.post('/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
    res.redirect('/dash')
})

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) {
            e.preventDefault();
            var data = $('input[name=number]').val();
            console.log(data)
            $.ajax({
                type: 'post',
                url: 'dash',
                data: data,
                dataType: 'text',
            })
                .done(function (data) {
                    var num = $('input[name=number]').val();
                    console.log(num)
                    $('input[name=number]').val(num);
                });
        });
    });

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();
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading