简体   繁体   中英

Using Ajax/jQuery to make POST request to insert row to mysql table on node js server

I have a form that takes in information such as name, age, etc, and the goal is to submit this information via the client side to insert this data into a mysql table row. However, I am not able to get the data to insert. Here is my client side JS code (the form id is 'form1' and the form submit button id is 'formSub', and the mysql table name is 'formTable'):

function insertData() {
    document.getElementById('formSub').addEventListener('click', function(event) {
        var formQuery = $("#form1").serialize();

        $.post('/insert', formQuery);
    });
}

This is my server side code (node.js):

app.post('/insert', function(req, res, next) {
    mysql.pool.query("INSERT INTO formTable (`name`, `age`, `city`) VALUES (?, ?, ?)", 
        [req.body.name, req.body.age, req.body.city], function(err, result) {
            if (err) {
                next(err);
                return;
            }
    });
});

This is the error I get:

POST http://ipaddress:3000/insert 500 (Internal Server Error)    jquery.min.js:4

Navigated to http://ipaddress:3000/?name=Bob&age=20&city=NYC

The form seems to be taking the data by looking at what is navigated to, but I don't see this data in the mysql table when I go to look at it in mysql. I'm not sure what to do.

"Navigated to http://ipaddress:3000/?name=Bob&age=20&city=NYC " Doesn't that mean it's somehow sending the data via GET and not POST if you're URL encoding?

Is this using Express 3 or 4?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM