Live Table Insert Update Delete in Node.js with MySQL

Live Table Add Edit Delete MySQL Data in Node.js" is a popular feature of web applications that allows users to manipulate data on a pa...

Live Table Insert Update Delete in Node.js with MySQL

Live Table Add Edit Delete MySQL Data in Node.js" is a popular feature of web applications that allows users to manipulate data on a page without having to refresh the page. This feature can be implemented using Node.js and MySQL, and in this article, we will walk through a step-by-step guide on how to create a live table that can add, edit and delete data using Node.js and MySQL.

To get started, we need to create a Node.js project and install the required dependencies. We can do this by running the following commands:


mkdir live_table_insert_update_delete
cd live_table_insert_update_delete
npm init -y
npm install express mysql body-parser


The above commands will create a new directory called live_table_insert_update_delete, initialize a new Node.js project and install the required dependencies.

Next, we need to create a MySQL database and table that we will use to store our sample data. We can do this by running the following SQL commands:


CREATE DATABASE testing;

USE testing;

CREATE TABLE sample_data (
  id int(11) NOT NULL AUTO_INCREMENT,
  first_name varchar(255) NOT NULL,
  last_name varchar(255) NOT NULL,
  age int(11) NOT NULL,
  PRIMARY KEY (id)
);


The above commands will create a new database called testing and a table called sample_data with four columns: id, first_name, last_name, and age.

Now we have create a new file called server.js and add the following code:

server.js

//imports the Express framework
const express = require('express');

//import mysql module
const mysql = require('mysql');

//import body-parser module
const bodyParser = require('body-parser');

//creates an instance of the Express application
const app = express();

// Add middleware for parse incoming request body
app.use(bodyParser.urlencoded({ extended : false }));

// Add middleware for parse incoming data in JSON
app.use(bodyParser.json());

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

//Check MySQL Database Connection
connection.connect((error) => {
	console.log('MySQL Database is connected Successfully');
});

//Create Route for Load index.html file
app.get("/", (request, response) => {
	response.sendFile(__dirname + "/index.html");
});

//Crate Route handle get request
app.get("/get_data", (request, response) => {
	const sql = `SELECT * FROM sample_data ORDER BY id ASC`;

	connection.query(sql, (error, results) => {
		console.log(error);
		response.send(results);

	});
});

//Create Route for Insert Data Operation
app.post("/add_data", (request, response) => {

	const first_name = request.body.first_name;

	const last_name = request.body.last_name;

	const age = request.body.age;

	const sql = `
	INSERT INTO sample_data 
	(first_name, last_name, age) 
	VALUES ("${first_name}", "${last_name}", "${age}")
	`;

	connection.query(sql, (error, results) => {
		response.json({
			message : 'Data Added'
		});
	});

});

//Create Route for Update Data Operation
app.post('/update_data', (request, response) => {

	const variable_name = request.body.variable_name;

	const variable_value = request.body.variable_value;

	const id = request.body.id;

	const sql = `UPDATE sample_data SET `+variable_name+`= "${variable_value}" WHERE id = "${id}"`;

	connection.query(sql, (error, results) => {

		response.json({
			message : 'Data Updated'
		});

	});

});

//Create Route for Delete data operation
app.post("/delete_data", (request, response) => {

	const id = request.body.id;

	const sql = `DELETE FROM sample_data WHERE id = '${id}'`;

	connection.query(sql, (error, results) => {
		response.json({
			message : 'Data Deleted'
		});
	});

});

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


This is a Node.js server-side code that creates a web application using the Express framework, and connects to a MySQL database to perform CRUD (Create, Read, Update, and Delete) operations. Here is a brief description of the code:

  1. Import the required modules: Express, MySQL, and body-parser.
  2. Create an instance of the Express application.
  3. Add middleware for parsing incoming request body, including JSON data.
  4. Create a MySQL database connection and check if it is connected successfully.
  5. Create a route to serve the index.html file.
  6. Create a route to handle GET requests and retrieve data from the MySQL database.
  7. Create a route to handle POST requests and insert data into the MySQL database.
  8. Create a route to handle POST requests and update data in the MySQL database.
  9. Create a route to handle POST requests and delete data in the MySQL database.
  10. Listen to the server on port 3000.

Overall, this code provides the backend functionality to serve a web application and perform CRUD operations on a MySQL database.





After this, we have to create index.html file for write HTML code and Vanilla JavaScript code.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Live Table Insert Update Delete in Node.js with MySQL</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-danger text-center"><b>Inline Table CRUD Operation in Node.js with MySQL - Delete Data</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Sample Data</div>
                <div class="card-body">
                    <table class="table table-bordered mt-3">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Age</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="results">

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

<script>

    const results_body = document.querySelector('#results');

    load_data();

    function load_data()
    {
        const request = new XMLHttpRequest();

        request.open(`get`, `/get_data`);

        let html = '';

        request.onreadystatechange = () => {
            if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
            {
                const results = JSON.parse(request.responseText);

                results.forEach(result => {
                    html += `
                    <tr>
                        <td>`+result.id+`</td>
                        <td contenteditable onblur="update_data(this, 'first_name', '`+result.id+`')">`+result.first_name+`</td>
                        <td contenteditable onblur="update_data(this, 'last_name', '`+result.id+`')">`+result.last_name+`</td>
                        <td contenteditable onblur="update_data(this, 'age', '`+result.id+`')">`+result.age+`</td>
                        <td><button type="button" class="btn btn-danger btn-sm" onclick="delete_data(`+result.id+`)">Remove</button></td>
                    </tr>
                    `;
                });

                html += `
                <tr>
                    <td></td>
                    <td contenteditable id="first_name_data"></td>
                    <td contenteditable id="last_name_data"></td>
                    <td contenteditable id="age_data"></td>
                    <td><button type="button" class="btn btn-success btn-sm" onclick="add_data()">Add</button></td>
                </tr>
                `;

                results_body.innerHTML = html;
            }
        };

        request.send();
    }

    function add_data()
    {
        const first_name = document.getElementById('first_name_data');

        const last_name = document.getElementById('last_name_data');

        const age = document.getElementById('age_data');

        const param = `first_name=`+first_name.innerText+`&last_name=`+last_name.innerText+`&age=`+age.innerText+``;

        const request = new XMLHttpRequest();

        request.open(`POST`, `/add_data`, true);

        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        request.onreadystatechange = () => {

            if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
            {
                alert("Data Added");

                load_data();
            }

        };

        request.send(param);
    }

    function update_data(element, variable_name, id)
    {
        const param = `variable_name=`+variable_name+`&variable_value=`+element.innerText+`&id=`+id+``;

        const request = new XMLHttpRequest();

        request.open(`POST`, `/update_data`, true);

        //Send the proper header information along with the request
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        request.onreadystatechange = () => {

            if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
            {

                alert('Data Updated');

            }

        };

        request.send(param);
    }

    function delete_data(id)
    {
        if(confirm("Are you sure you want to remove it?"))
        {
            const param = `id=`+id+``;

            const request = new XMLHttpRequest();

            request.open('POST', `/delete_data`, true);

            request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            request.onreadystatechange = () => {

                if(request.readyState === XMLHttpRequest.DONE && request.status === 200)
                {
                    alert('Data Deleted');

                    load_data();
                }

            };

            request.send(param);
        }
    }

</script>


This code is a web page with a table that performs CRUD (Create, Read, Update, Delete) operations in Node.js with MySQL. The table is displayed in a Bootstrap card, and it shows a list of people with their IDs, first and last names, email, and gender. The table can be edited inline, and it has an "Add" button that adds a new row to the table, a "Remove" button that deletes a row from the table, and an "Update" button that updates the data in the table.

The JavaScript code uses XMLHttpRequest to send asynchronous HTTP requests to the server-side Node.js application, which interacts with a MySQL database to perform the CRUD operations. The load_data() function sends a GET request to the server-side application to retrieve the data and displays it in the table using HTML. The add_data(), update_data() and delete_data() functions send POST requests to the server-side application to perform the corresponding operations.

In conclusion, the Live Table Add Edit Delete MySQL Data in Node.js is a web application that allows users to perform basic CRUD (Create, Read, Update, and Delete) operations on a MySQL database using Node.js. The application uses an HTML table to display the data from the database, which can be edited, updated, and deleted in real-time. The code uses AJAX requests to communicate with the server-side Node.js application, which handles the database operations. This application can be useful for developers who want to learn how to build a basic CRUD application using Node.js and MySQL or for those who need a simple way to manage data stored in a MySQL database.

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: Live Table Insert Update Delete in Node.js with MySQL
Live Table Insert Update Delete in Node.js with MySQL
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiio172xpMb0lXGn8MlCmY6j48SDlzSpWrNOo3nBHhHtH-cGTe73npIft8JgtrL0UA59V-zMhQj6iY7U1mddvJ8cXxY8bPPGj1MSS9DS1p6nHqDMWJRP8fAfJrxWcB9PaeVznJG6fukG9cuilx1xLSTj5-IYTcm028SA6lfAkKiqFXdjU_v8bCxlawYvQ/s16000/live-add-edit-delete-blog.jpg
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiio172xpMb0lXGn8MlCmY6j48SDlzSpWrNOo3nBHhHtH-cGTe73npIft8JgtrL0UA59V-zMhQj6iY7U1mddvJ8cXxY8bPPGj1MSS9DS1p6nHqDMWJRP8fAfJrxWcB9PaeVznJG6fukG9cuilx1xLSTj5-IYTcm028SA6lfAkKiqFXdjU_v8bCxlawYvQ/s72-c/live-add-edit-delete-blog.jpg
kumpulan driver
https://kepsuk.blogspot.com/2023/04/live-table-insert-update-delete-in_6.html
https://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/2023/04/live-table-insert-update-delete-in_6.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