Saturday, 7 October 2023

Display Dynamic MySQL Data in Bootstrap 5 Offcanvas Using Node.js: A Step-by-Step Guide


Introduction


In the world of web development, creating dynamic and interactive user interfaces is essential. Bootstrap 5, a popular front-end framework, provides the tools to do just that. Node.js, a server-side runtime, allows us to handle server logic efficiently. In this step-by-step guide, we will combine the power of Bootstrap 5 and Node.js to display dynamic data from a MySQL database within a Bootstrap 5 Offcanvas component.

Prerequisites:


  • Basic knowledge of HTML, CSS, and JavaScript
  • Node.js and npm (Node Package Manager) installed on your system
  • A MySQL database with some sample data

Let's dive into the process of building a dynamic web application that fetches data from a MySQL database and presents it beautifully in a Bootstrap 5 Offcanvas.


Display Dynamic MySQL Data in Bootstrap 5 Offcanvas Using Node.js: A Step-by-Step Guide


Table of Contents


  1. Setting Up Your Development Environment
  2. Creating the MySQL Database
  3. Building the Node.js Server
  4. Fetching Data from the MySQL Database
  5. Creating the Bootstrap 5 Offcanvas
  6. Displaying Dynamic Data in the Offcanvas
  7. Testing and Troubleshooting
  8. Conclusion and Next Steps

1. Setting Up Your Development Environment


Before we start coding, let's ensure that our development environment is properly configured. We'll need Node.js, npm, and any code editor of your choice. Once you have these in place, we can proceed to create our MySQL database.

So for Setting Up Development Environment, first we have goes to terminal and goes into our working directory and run this command which will download and install Express framework and Mysql2 Node.js module.


npm install express mysql2


2. Creating the MySQL Database


We'll design a MySQL database to store the data we want to display on our website. We'll cover database schema, table creation, and data insertion. So by executing below .sql script will create tbl_employee table with sample data in your MySQL database.


--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Parker', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, '15900.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=212;


3. Building the Node.js Server


In this section, we'll set up a Node.js server using Express.js, a popular Node.js framework, and configure it to communicate with our MySQL database.

server.js

const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const path = require('path');

const app = express();

//app.use(bodyParser.urlencoded({ extended :true }));

// Configure body parser to handle JSON data
app.use(bodyParser.json());

// Serve static files from the "images" folder
app.use(express.static(path.join(__dirname, 'images')));

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', err);
		return;
	} 
	console.log('Connected to MySQL database');
});


This code will create node server and include required dependencies and then after we have make MySQL database connection also.

4. Fetching Data from the MySQL Database


Learn how to use Node.js to retrieve data from the MySQL database and prepare it for display.

So first we have to create data.html and under this, we have to create HTML table structure and then after we have to write JavaScript code for fetch data from MySQL table and display on web page in tabular format.

data.html

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

        <title>Node.js Display Dynamic MySQL Data in Bootstrap 5 Offcanvas</title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-primary mt-5 text-center">Node.js Display Dynamic MySQL Data in Bootstrap 5 Offcanvas</h1>
            <div class="card mt-5">
                <div class="card-header">
                    <b>Node.js Display Dynamic MySQL Data in Bootstrap 5 Offcanvas</b>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Employee Name</th>
                                    <th>Position</th>
                                </tr>
                            </thead>
                            <tbody id="employee_table"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </body>
</html>

<script>

    loadData();

    function loadData(id = ''){
        const request = {
            method : 'POST',
            headers : {
                'Content-Type': 'application/json'
            },
            body : JSON.stringify({ id })
        };

        fetch('/fetchData', request)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            let html = '';
            if(id === ''){
                data.result.map((row) => {
                    html += `
                    <tr onclick="loadData('${row.id}');" style="cursor:pointer">
                        <td>${row.name}</td>
                        <td>${row.designation}</td>
                    </tr>
                    `;
                });

                const tableBody = document.querySelector('#employee_table');

                tableBody.innerHTML = html;
            }
        })
    }

</script>


server.js

app.get('/', (request, response) => {
	response.sendFile(__dirname + '/data.html');
});

app.post('/fetchData', (request, response) => {
	const id = request.body.id;

	let query;

	if(id === ''){
		query = `SELECT id, name, designation FROM tbl_employee ORDER BY id DESC`;
	} else {
		query = `SELECT * FROM tbl_employee WHERE id = ${id}`;
	}

	connection.query(query, (error, result) => {
		response.json({result});
	});
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
});


5. Creating the Bootstrap 5 Offcanvas


Here, we'll dive into the front-end development aspect and create a Bootstrap 5 Offcanvas component that will elegantly slide in and out to display our dynamic data.

data.html

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvas_component" style="width: 250px;">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title">Employee Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body"></div>
        </div>


6. Displaying Dynamic Data in the Offcanvas


We'll integrate the data fetched from the database into our Bootstrap 5 Offcanvas, making it interactive and user-friendly.

data.html

<script>

    let offcanvas;

    let offcanvas_body = document.querySelector('.offcanvas-body');

    let offcanvas_component = document.querySelector('#offcanvas_component');

    offcanvas = new bootstrap.Offcanvas(offcanvas_component);

    loadData();

    function loadData(id = ''){
        const request = {
            method : 'POST',
            headers : {
                'Content-Type': 'application/json'
            },
            body : JSON.stringify({ id })
        };

        fetch('/fetchData', request)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            let html = '';
            if(id === ''){
                data.result.map((row) => {
                    html += `
                    <tr onclick="loadData('${row.id}');" style="cursor:pointer">
                        <td>${row.name}</td>
                        <td>${row.designation}</td>
                    </tr>
                    `;
                });

                const tableBody = document.querySelector('#employee_table');

                tableBody.innerHTML = html;
            } else {
                html += `<div class="card">`;
                data.result.map((row) => {
                    html += `
                    <img src="/${row.images}" class="rounded-circle" />
                    <div class="card-body">
                        <h5 class="card-title">${row.name}</h5>
                        <p class="card-text">${row.address}</p>
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item"><b>Gender : </b>${row.gender}</li>
                        <li class="list-group-item"><b>Designation : </b>${row.designation}</li>
                        <li class="list-group-item"><b>Age : </b>${row.age}</li>
                    </ul>
                    `;
                });
                html += `</div>`;

                offcanvas_body.innerHTML = html;

                offcanvas.show();
            }
        })
    }

</script>





7. Testing and Troubleshooting


Let's test our application, identify and troubleshoot any issues that may arise, and ensure that everything works as expected.

So we have goes to terminal and run following command, which will start our node server.


node server.js


After run this command it will start node server and provide us base url of our node application.


http://localhost:3000/


So by open this command in the browser we can check our How to display dynamic MySQL data in Bootstrap 5 Offcanvas with Node.js Application.

8. Conclusion and Next Steps


In the final section, we'll recap what we've learned and discuss potential next steps, such as adding additional features or deploying the application to a live server.

By the end of this step-by-step guide, you'll have a fully functional web application that can display dynamic data from a MySQL database in a Bootstrap 5 Offcanvas using Node.js. Let's get started!

Complete Source Code


data.html

<script>

    let offcanvas;

    let offcanvas_body = document.querySelector('.offcanvas-body');

    let offcanvas_component = document.querySelector('#offcanvas_component');

    offcanvas = new bootstrap.Offcanvas(offcanvas_component);

    loadData();

    function loadData(id = ''){
        const request = {
            method : 'POST',
            headers : {
                'Content-Type': 'application/json'
            },
            body : JSON.stringify({ id })
        };

        fetch('/fetchData', request)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            let html = '';
            if(id === ''){
                data.result.map((row) => {
                    html += `
                    <tr onclick="loadData('${row.id}');" style="cursor:pointer">
                        <td>${row.name}</td>
                        <td>${row.designation}</td>
                    </tr>
                    `;
                });

                const tableBody = document.querySelector('#employee_table');

                tableBody.innerHTML = html;
            } else {
                html += `<div class="card">`;
                data.result.map((row) => {
                    html += `
                    <img src="/${row.images}" class="rounded-circle" />
                    <div class="card-body">
                        <h5 class="card-title">${row.name}</h5>
                        <p class="card-text">${row.address}</p>
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item"><b>Gender : </b>${row.gender}</li>
                        <li class="list-group-item"><b>Designation : </b>${row.designation}</li>
                        <li class="list-group-item"><b>Age : </b>${row.age}</li>
                    </ul>
                    `;
                });
                html += `</div>`;

                offcanvas_body.innerHTML = html;

                offcanvas.show();
            }
        })
    }

</script>


server.js

const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const path = require('path');

const app = express();

// Configure body parser to handle JSON data

app.use(bodyParser.json());

// Serve static files from the "images" folder
app.use(express.static(path.join(__dirname, 'images')));

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', err);
		return;
	}
	console.log('Connected to MySQL database');
});

app.get('/', (request, response) => {
	response.sendFile(__dirname + '/data.html');
});

app.post('/fetchData', (request, response) => {
	const id = request.body.id;

	let query;

	if(id === ''){
		query = `SELECT id, name, designation FROM tbl_employee ORDER BY id DESC`;
	} else {
		query = `SELECT * FROM tbl_employee WHERE id = ${id}`;
	}

	connection.query(query, (error, result) => {
		response.json({result});
	});
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
});

0 comments:

Post a Comment