简体   繁体   中英

insert html table data into mysql database in node js

I am trying to retrieve data from a html table and insert this in MySQL database. I am already able to do the reverse, which is retrieve the information from the database and display it in same table using ejs template. I can also insert raw/JSON data into MySQL, but I'm unable to extract the data from same table because I am unable to reference that table from the server side (the same way body parser does with form data).

I have searched the web, all tutorials just do an insert to database using json data, nobody is retrieving data first from html table.

With below code I can loop through table data using plain javascript.

var table = document.getElementById('vehiclesTB');
for (var i = 1; i < table.rows.length; i++) {
  if (table.rows[i].cells.length) {
    var vehicleTag = (table.rows[i].cells[0].textContent.trim());    
  }
}

How do I pass retrieve data from html table to my controller(server side)? I am unable to reference html table directly from my server file (app.js).

My app.js file:

var express = require('express')
  , routes = require('./routes')
  , controls = require('./routes/controls')
  , http = require('http')
  , path = require('path');
var app = express();
var mysql = require('mysql');
var bodyParser =require("body-parser");
var pool = mysql.createConnection({
    connectionLimit: 100,
    host: 'localhost',
    database: 'vehicluster',
    user: 'motor',
    password: '',
    debug: false  
});

pool.connect();



// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

app.post('/vehicle', controls.vehicle);
//Middleware
app.listen(8080)

My controls.js file.

exports.vehicle = function(req, res){                   
var table = document.getElementById('vehiclesTB');//how to read this 
table in ejs
for (var i = 1; i < table.rows.length; i++) {
if (table.rows[i].cells.length) {
var vehicleTag = (table.rows[i].cells[0].textContent.trim());
var vehicleMake = (table.rows[i].cells[1].textContent.trim());
var vehicleModel = (table.rows[i].cells[2].textContent.trim());
var price = (table.rows[i].cells[3].textContent.trim());
var quantity = (table.rows[i].cells[4].textContent.trim());                
     }
}

var sql = 'insert into Vehicle(make, model, price, quantity) values 
(?,?,?,?,?)';
pool.query(sql,[vehicleMake, vehicleModel, price, quantity], 
(err,data)=>{
if(err){
    console.log(err);            
    return
 }else{
    console.log(data);                        
     }      
 };

The HTML table is showing relevant item (table), place table data into mysql database. I can already retrieve to table:

<div style="overflow-x: auto;">                       
    <table id="customers">
        <tbody id="mytbody">
            <tr>                                  
                <th>Make</th> 
                <th>Model</th>
                <th>price</th>
                <th>quantity</th>                                                                   
            </tr>
            <tr>
                <th>toyota</th> 
                <th>camry</th>
                <th>200</th>
                <th>5</th>                                     
            </tr>
            <tr>
                <th>honda</th> 
                <th>civic</th>
                <th>400</th>
                <th>7</th>                                     
            </tr>
        </tbody>
    </table>                            
</div>

I am getting errors as you would expect, getElementById is client side, null value etc, database is not updated. Most tutorials online show the reverse, which is to insert database values into html table, instead of the other way around. Any help with real table example/route will be appreciated.

If you need to have a client-side HTML table made available on the server, then you will need to add an ajax endpoint at the server and code to send the HTML data (see the axios library).

I am not sure of your use case as it seems the data at the client side should already be available at the server since you rendered it. It may not be in HTML, but the data should exist there. Unless of course you are getting the HTML table from another source (or perhaps this is just an exercise in HTML parsing??).


Here is an update to show how to use axios. Note though that you still need to investigate that library to learn how to handle errors or even if you need to do other things upon success.

In your front end:

var table = document.getElementById('vehiclesTB');
var postBody = [];
for (var i = 1; i < table.rows.length; i++) {
  if (table.rows[i].cells.length) {
    var vehicle = {
      vehicleTag: (table.rows[i].cells[0].textContent.trim())
      vehicleMake: (table.rows[i].cells[1].textContent.trim()),
      vehicleModel: (table.rows[i].cells[2].textContent.trim()),
      price: (table.rows[i].cells[3].textContent.trim()),
      quantity: (table.rows[i].cells[4].textContent.trim())
    }
    postBody.push(vehicle);
  }

}

axios({ // should add error handling as appropriate
  method: 'post',
  url: '/vehicle',
  data: postBody
});

Then on your server side, modify your controls.js:

exports.vehicle = function(req, res) {
  var table = req.body; // assumes you have used bodyparser middleware to parse JSON into an object
  for (var i = 1; i < table.length; i++) {
    var vehicle = table[i];
    var sql = 'insert into Vehicle(make, model, price, quantity) values ( ? , ? , ? , ? , ? )';
    pool.query(sql, [vehicle.vehicleMake, vehicle.vehicleModel, vehicle.price, vehicle.quantity],
      (err, data) => {
        if (err) {
          console.log(err);
          return
        } else {
          console.log(data);
        }
      });
  }
};

Also, I would suggest you look at Array.forEach for looking over an array instead of the for loop method you are using (see MDN documentation)

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