Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

I am learning how to use node.js with MySQL. Now I can able to get my MySQL data shown in the browser however I need to handle it through my index.html and a CSS file at some point.

This is my app.js:

// moduels
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('bodyParser')

// 
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: false}));

// connect to database
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "1234",
    database: "BathBombs_DB"
});

// routes
app.get('/', function(request, response){
    console.log('GET request received at /') 
    con.query("SELECT * FROM customers", function (err, result) {
        if (err) throw err;
        else{
            response.send(result)
        }

    });
});

// listen for trafic and display on localhost:9000
app.listen(9000, function () {
    console.log('Connected to port 9000');
});

My index.html site appears like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <form action="/" method="POST">
            <table type="text" name="firstname" ></table>
    </form>

</body>
</html>

1 Answer

0 votes
by (12.7k points)

You need to make an ajax call to get a result from the server and bind with HTML content using javascript as below :

HTML template

 <table id="tableData" class="table table-fixed">
<thead>
  <tr>
  </tr>
</thead>
<tbody class="tbody" >
</tbody>

Following is the script to make an ajax call:

$(document).ready(() => {

$.ajax({
    url: "http://localhost:9000/list", 
    method: 'GET',
    success: function(response){
        if(response.rows.length > 0){
            for(let index = 0; index < response.rows.length; index++) {
                var newRow = $("<tr>");
                var cols = "";
                var firstname = '';
                var lastname = '';
                var gender = '';
                cols += '<td> '+ response.rows[index].firstname +'</td>';
                cols += '<td> '+ response.rows[index].lastname +'</td>';
                cols += '<td> '+ response.rows[index].gender+'</td>';                
                newRow.append(cols);
                $("#tableData .tbody").append(newRow);
            }  

        }
    }
})
})

Interested to Learn SQL in detail? Join the SQL Training course by Intellipaat.

Related questions

Browse Categories

...