0

Hello i have problem with getting input from html to node and send it to databse. What I am getting now is input type "undefined". So if someone could help me I would really preciate it. down here is my code html and node.js

          |  |
          |  |
          |  |
        \      /
         \    /
          \  /
           \/

HTML

<form action="database" method="POST">
  <div class="form-group" id="test">
    <label for="fname">First name</label>
    <input type="text" id="fname" placeholder="First name: " name="fname">
  </div>
  <div class="form-group">
    <label for="lname">Last name</label>
    <input type="text" id="lname" placeholder="Last name: " name="lname">
  </div>
  <div class="form-group">
    <label for="state">state: </label>
    <input type="text" id="state" name="state" placeholder="sate: ">
  </div>        
 
</form>

NODE.js

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "test"
  });

var fname = req.body.fname;
var lname = req.body.lname;
var state = req.body.state;






con.connect(function(err) {
    if (err) throw err;
    var sql = `INSERT INTO customers (c_fname, c_lname, c_state) VALUES ("${fname}", "${lname}", "${state}")`;
    con.query(sql, function (err, result) {
    if (err) throw err;
       console.log("1 record inserted, ID: " + result.insertId);
                      
    });
});

1 Answer 1

1

It seems you are missing crucial parts. I'd recommend going through some tutorials/videos to understand how the request-response works on the web. Since you are using Node.js, this article explains how to deal with forms using express.js as the application server.

request-response sample flow chart. source: MDN

Assuming index.html and index.js (your node.js file) is in the same folder, you could do,

const express = require('express');
var bodyParser = require('body-parser')
const app = express();
  
var urlencodedParser = bodyParser.urlencoded({ extended: false })
    
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
    
app.post('/', urlencodedParser, (req, res) => {
    console.log('Got body:', req.body); // add logic to insert into db here.
    res.sendStatus(200);
});
    
app.listen(3000);

Also, it seems you are missing submit button in your html.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.