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-...


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');
});

COMMENTS

Nama

Add,1,Ajax,2,ajax tutorial,1,Ajax with javascript,1,Ajax with node.js,1,application,2,array,1,array to string,1,array to string conversion nodejs,1,array to string in node js,1,array to string nodejs,1,Asynchronous JavaScript,1,authentication,1,authentication node js,1,authorization,1,availability,1,backend,1,bootstrap offcanvas dynamic content,1,bootstrap offcanvas dynamic content node.js,1,bootstrap offcanvas dynamic data,1,bootstrap offcanvas remote dynamic content,1,cart,1,centos 7,1,centos7,1,check,1,contact form node js,1,contact form nodemailer,1,contact us form node,1,conversion,1,create,1,crud,4,crud application,1,crud operation in node js,1,crud operation in node js with mysql,1,CSS,1,data,1,database,1,databases,1,datatables,1,DataTables integration in React.js,1,date range,1,delete,2,download,1,drag &amp; drop,1,drag and drop,1,drag and drop files,1,drag and drop multiple file,1,drag n drop,1,dynamic dropdown in react js,1,dynamic dropdown in react.js,1,ecommerce,2,edit,1,educational project,1,email address,1,email verification,1,email verification using jwt,1,express,3,expressjs,1,fetch,1,file upload,1,file upload in node js,1,files,1,filter,1,Front-end development tutorial,1,Frontend,1,GET,1,how to send email using node js,1,how to send emails in node js,1,html,1,html 2 pdf,1,html to pdf,1,html to pdf node,1,insert,2,insert data in mysql node js,1,Javascript,3,JavaScript tutorial,1,join array nodejs,1,js,1,json,1,jwt,3,jwt authentication,2,jwt authentication node js,1,jwt authentication php,1,jwt email verification,1,jwt login,1,jwt login php,1,jwt php example,1,jwt token,1,jwt token email verification,1,laravel 10,1,laravel 10 tutorial,1,laravel datatables,1,laravel datatables date range filter,1,laravel date filter,1,laravel date range filter,1,last insert id in node,1,learn reactjs,1,linux,1,live,2,live check email address availability,1,live search,1,load more data on click,1,load more data on click javascript,1,load more javscript node.js,1,load more nodejs,1,load more results,1,load more results with node js and ajax,1,login,1,merge 2 arrays in node js,1,merge array in nodejs,1,merge array node,1,merge two array in node js,1,MongoDB,1,mongodb crud,1,mongodb crud operations,1,multer,1,multiple file upload,1,mysql,7,mysql 8,1,mysql tutorial,1,mysql8,1,node,3,node js,8,node js array merge,1,node js array to string,1,node js crud,2,node js crud mysql,1,node js crud operation with mysql,1,node js load more pagination,1,node js mongodb crud,1,node js mysql last insert id,1,node js tutorial,2,node mongodb crud,1,node mysql get last insert id,1,node pdf,1,node.js,8,node.js array,1,node.js crud,1,node.js mysql,1,node.js tutorial,2,nodejs,9,nodejs array,1,nodejs array merge,1,nodejs create pdf,1,nodejs crud,1,nodejs pdf,1,nodejs pdf create,1,nodejs programming,1,offcanvas,1,open source,1,Optimizing web application performance,1,parking management system,1,parking management system in php,1,parking management system project,1,password,1,pdf-creator-node,1,php,3,php jwt authentication example,1,php jwt login,1,php login jwt,1,php parking management system,1,php project,1,PHP server-side processing,1,populate dropdown from database,1,programming tutorial,1,project,1,Puppeteer,1,Puppeteer HTML to PDF,1,React,1,react file upload,1,react js,2,react js dynamic dropdown,1,react js file upload validation,1,react js tutorial,1,react php myql,1,React.js,1,react.js dependent select,1,react.js file upload,1,Reactjs,4,reactJS CRUD,1,reactjs file upload,1,reactjs file upload app,1,reactjs file upload sample code,1,reactjs tutorial,1,read,1,register,1,registration,2,remove,1,request form node,1,reset,1,search,1,select,1,send activation email php,1,sending email using node js,1,server,1,Server-side data processing,1,shopping cart,1,shopping cart in node js,1,shopping cart javascript,1,shopping cart project in javascript,1,shopping cart using node js,1,shopping-cart,1,society management system in php,1,society management system php,1,society management system php source code,1,society management system project in php,1,society management system project php,1,source code,1,string,1,token,2,tutorial,8,update,2,using jwt for email verification,1,vanilla,1,vite,1,vitejs,1,vitejs crud app,1,web development,7,Web development guide,1,webslesson,2,what is jwt authentication,1,
ltr
item
kumpulan driver: Display Dynamic MySQL Data in Bootstrap 5 Offcanvas Using Node.js: A Step-by-Step Guide
Display Dynamic MySQL Data in Bootstrap 5 Offcanvas Using Node.js: A Step-by-Step Guide
https://i.ytimg.com/vi/DL-cVpVKpUw/hqdefault.jpg
https://i.ytimg.com/vi/DL-cVpVKpUw/default.jpg
kumpulan driver
https://kepsuk.blogspot.com/2023/10/display-dynamic-mysql-data-in-bootstrap_7.html
https://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/2023/10/display-dynamic-mysql-data-in-bootstrap_7.html
true
6399859916032798219
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content