简体   繁体   中英

Insert INTO MySQL Table from HTML simple form using node.js and JavaScript

OK, after 3 days trying hard, I got stucked at a point where I just simply feel totally overwhelmed. I feel like a little kid lost in the inmense and unknown world Web Development is (I work as mainframe developer) and started to feel frustrated really much, so I decided to ask for serious help. I wont post any code, since it wont help in any degree.

What I want and still cant achieve:

  • Enter " localhost:8080/datos.html ", which has 2 "textbox", and a button. After pressing the button, I want the data of the 2 textbox ("name" and "password") be stored in a MySQL database, using Node.js.

The situation is as follows:

  • Im using Windows 7.
  • Node.js is installed on my PC, I can do "node server.js" in the cmd terminal and the thing gonna work just fine.
  • I can, in the 'server.js', connect to the MySQL Database and make a query, the result is OK, I can do an Insert into as well, everything's fine.
  • In the same folder ' example.js ' file is, I have a file named ' datos.html '.
  • Using "url parsing", I managed to write "localhost:8080/datos.html" in the browser (chrome) so that 'datos.html' is displayed correctly (the 2 textbox and the button displays correctly) after starting the 'server.js' via Node.js.

Now the problem begins: there's simply NO way I can manage to insert the data of the textbox in the MySQL database... As I said, inserting data via server.js is not a problem, neither is 'getting' the textbox values with 'document.getElementByI()' from the server.js. The problem is, I cant find the way to acomplish this. I know this is probably a lame question, and was thinking about not making it, but god, for a guy who is used to COBOL, JCL and CICS, web development is just too painful.

As a reference, I read 'tutorials' and guides from W3Schools about HTML, Ajax, Node.js, can do the examples shown in there, but just cant LINK the things to make everything a SINGLE functional thing.

Note that my problem is not ' technical ', I know how to query a SQL table, or to 'start' node (in a basic way, tho), I know how to make a (way too) simple HTML and display it from node.js; but the problem is about 'how to do something', which is simple but I just simply cant achieve yet.

Any videos, manuals, tutorials, course, or whatever you have to help me achieve this simple thing, gonna be really apreciated.

You are on the right track. In order to achieve the desired objective do the following.

1) You can use express as Jason mentioned in the previous answer and handle everything for now as an application with the client and server on the same machine for testing as I have done in my application until you are ready to segregate the client server from one another.

2) In order to use MySQL as the storage engine as opposed to what I used SqlLite use the example from https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });
});

3) Create an HTML file to handle input as shown below

4) Create a client.js file to send the request to NodeJS server

5) Create server.js file to receive request and handle insert using in my case SQLite

6) In order to create database run the following in glitch console

~sqlite demo      <---demo is name of db in sqlite3
% create table userlist(user, password);
CTRL+D            <---exit

7) Locating a suitable online resource took some effort but I located a place where one can edit nodejs projects for viewing

I found this: https://flaviocopes.com/nodejs-hosting/ and located a online environment tool called Glitch

Try the following example I constructed at Glitch which can be viewed edited and run once you click on the Show Live button in green.

https://glitch.com/edit/#!/node-js-demo-stack-overflow?path=public/client.js:1:0

client.js

// client-side js
// run by the browser each time your view template referencing it is loaded

console.log('Testing Add');

function submit()
{
  // request the user from our app's sqlite database
  const userRequest = new XMLHttpRequest();
  userRequest.open('post', '/addUser');
  userRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
  userRequest.send(JSON.stringify({'user':document.getElementById("user").value, 'password': document.getElementById("password").value}));
}

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Welcome to Glitch!</title>
    <meta name="description" content="A cool thing made with Glitch">
    <link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css">
    
    <!-- import the webpage's client-side javascript file -->
    <script src="/client.js"></script>
  </head>
  <body>
    <input type="text" id="user"/>
    <input type="text" id="password"/> 
    <button onclick="submit()">Send</button>
  </body>
</html>

server.js

// server.js
// where your node app starts

// init project
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//
// we've started you off with Express, 
// but feel free to use whatever libs or frameworks you'd like through `package.json`.

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// init sqlite db
var fs = require('fs');
var dbFile = 'demo';
var exists = fs.existsSync(dbFile);
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(dbFile);

// create application/json parser
var jsonParser = bodyParser.json();


// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

// endpoint to addUser in the database
// currently this is the only endpoint, ie. adding dreams won't update the database
// read the sqlite3 module docs and try to add your own! https://www.npmjs.com/package/sqlite3
app.post('/addUser', jsonParser, function(request, response) {
 
  
// if ./.data/sqlite.db does not exist, create it, otherwise print records to console
  if (!exists) {
    console.log("Table not found");
    db.run('CREATE TABLE userlist (user text, password text');
    console.log('New table User List Created!');
    insert(request);
  }
  else{
    insert(request);
  }
  db.each('SELECT * from userlist', function(err, row) {
      if ( row ) {
        console.log('record:', JSON.stringify(row));
      }
    });
});

var insert = function (req)
{
    db.run('INSERT INTO userlist (user, password) VALUES ("'+req.body.user+'","'+req.body.password+'")');
}
    
// listen for requests :)
var listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' + listener.address().port);
});

Insert this in the else block of the post handler in server.js under insert(request) to be able to send back table values and view in client

db.all('SELECT * from userlist', function(err, rows) {
        response.send(rows);
    });

Insert this in submit function in client.js to view table values on submit

userRequest.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var rows = JSON.parse(this.responseText);
    var tbl = "<table border=1>";
    tbl += "<thead><td>Name</td><td>Password</td></thead>";
    for (var i = 0; i < rows.length; i++)
    {
      tbl+="<tr><td>"+rows[i].user+"</td><td>"+rows[i].password+"</td></tr>";
      console.log('record:', JSON.stringify(rows[i]));
    }
    tbl += "</table>";
    document.getElementById("tbl").innerHTML = tbl;
  }
}

If you're not already, you should probably be using a Node framework that will serve as your router for incoming requests. The most popular one out there for many years is Express.

https://expressjs.com/

Once you do that you'll be able to handle requests like

app.get("/datos", (req, res) => {
        // Serve the form logic here
    });

app.post("/datos", (req, res) => {
        // Handle the form submission logic here
    });

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