Ajax Live Search using Node.js with MySQL

In today's fast-paced world, users expect web applications to be responsive and efficient. One of the ways to achieve this is by impleme...


In today's fast-paced world, users expect web applications to be responsive and efficient. One of the ways to achieve this is by implementing an Ajax live search feature on your website. This feature allows users to search for content on your website without having to reload the page. In this article, we will show you how to implement an Ajax live search feature using Node.js and MySQL.

Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to build server-side applications with JavaScript. MySQL is a popular open-source relational database management system that is widely used in web development. Together, they provide a powerful combination for building web applications.

To get started, you will need to have Node.js and MySQL installed on your machine. You will also need to have a basic understanding of JavaScript, HTML, and CSS.


Ajax Live Search using Node.js with MySQL


Step 1: Setting up the Database


The first step is to set up the database. You will need to create a table to store the data that will be searched. For this example, we will create a table called "customers" with columns for "customer_id", "customer_first_name", "customer_last_name", "customer_email" and "customer_gender". Below you can find .sql script for create customers table and it will insert some sample data into that table.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL,
  `customer_first_name` varchar(200) NOT NULL,
  `customer_last_name` varchar(200) NOT NULL,
  `customer_email` varchar(300) NOT NULL,
  `customer_gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`customer_id`, `customer_first_name`, `customer_last_name`, `customer_email`, `customer_gender`) VALUES
(1, 'Mathilda', 'Garnam', 'mgarnam0@rediff.com', 'Female'),
(2, 'Tymon', 'McEniry', 'tmceniry1@free.fr', 'Male'),
(3, 'Margarette', 'Danilyak', 'mdanilyak2@joomla.org', 'Female'),
(4, 'Ermanno', 'Huebner', 'ehuebner3@wikipedia.org', 'Male'),
(5, 'Agnes', 'Barabich', 'abarabich4@delicious.com', 'Female'),
(6, 'Hamil', 'De Zuani', 'hdezuani5@hostgator.com', 'Male'),
(7, 'Corrie', 'Althorpe', 'calthorpe6@themeforest.net', 'Female'),
(8, 'Ricard', 'Dumelow', 'rdumelow7@china.com.cn', 'Male'),
(9, 'D\'arcy', 'Crayton', 'dcrayton8@furl.net', 'Male'),
(10, 'Kayle', 'Stonier', 'kstonier9@thetimes.co.uk', 'Female'),
(11, 'Julissa', 'Bogeys', 'jbogeysa@w3.org', 'Female'),
(12, 'Saul', 'Hyam', 'shyamb@senate.gov', 'Male'),
(13, 'Saleem', 'Pettengell', 'spettengellc@si.edu', 'Male'),
(14, 'Ives', 'Osmon', 'iosmond@forbes.com', 'Male'),
(15, 'Wendie', 'Acton', 'wactone@army.mil', 'Female'),
(16, 'Ches', 'Redd', 'creddf@un.org', 'Male'),
(17, 'Sarine', 'Cossum', 'scossumg@hubpages.com', 'Female'),
(18, 'Farly', 'Arsmith', 'farsmithh@linkedin.com', 'Male'),
(19, 'Althea', 'Tavernor', 'atavernori@printfriendly.com', 'Female'),
(20, 'Gayla', 'Billes', 'gbillesj@miitbeian.gov.cn', 'Female'),
(21, 'Teodoor', 'Shreenan', 'tshreenank@hp.com', 'Male'),
(22, 'Rich', 'Frusher', 'rfrusherl@cbc.ca', 'Male'),
(23, 'Lissie', 'Glazier', 'lglazierm@elpais.com', 'Female'),
(24, 'Glyn', 'Dealey', 'gdealeyn@unesco.org', 'Male'),
(25, 'Kathy', 'Swansborough', 'kswansborougho@amazon.de', 'Female'),
(26, 'Dudley', 'Hopkyns', 'dhopkynsp@mozilla.com', 'Male'),
(27, 'Byran', 'Ealles', 'beallesq@engadget.com', 'Male'),
(28, 'Kenon', 'MacGray', 'kmacgrayr@stumbleupon.com', 'Male'),
(29, 'Sibilla', 'Norres', 'snorress@smugmug.com', 'Female'),
(30, 'Melita', 'Redman', 'mredmant@a8.net', 'Female'),
(31, 'Ki', 'Brydson', 'kbrydsonu@google.ca', 'Female'),
(32, 'Bernardine', 'Follis', 'bfollisv@unc.edu', 'Female'),
(33, 'Farleigh', 'Sudy', 'fsudyw@unc.edu', 'Male'),
(34, 'Belle', 'Dearness', 'bdearnessx@google.co.uk', 'Female'),
(35, 'Onfre', 'Kee', 'okeey@archive.org', 'Male');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`customer_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;


Step 2: Setting up the Server


Next, we will set up the server using Node.js. We will use the Express framework to handle the HTTP requests and responses. You can install Express using npm, the package manager for Node.js, by running the following command in your terminal:


cd f:

In my computer, We will create node application in f: drive, so we have goes into this f: drive.


cd node

After this we have goes into node in which we will create Ajax Live data Search Node Application.


mkdir ajax_live_data_search

This command will create ajax_live_data_search directory under node directory.


cd ajax_live_data_search

After this we have goes inti this ajax_live_data_search directory in which we will download different node module.


npm install express mysql

This command will download Node Express Module and MySQL Module under this ajax_live_data_search directory.





After installing Express, create a new file called "app.js" and add the following code:

app.js

const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000;

const pool = mysql.createPool({
	connectionLimit : 10,
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

app.get('/', (request, response) => {

	response.sendFile(__dirname + '/index.html');

});

app.listen(port, () => {

	console.log(`Server listening on port ${port}`);

});


This code sets up a basic Express server that listens on port 3000. You can test that the server is working by running "node app.js" in your terminal and navigating to "http://localhost:3000" in your browser and it will load HTML content of index.html file.

Step 3: Implementing the Ajax Live Search


Now we will implement the Ajax live search feature. We will use Vanilla JavaScript to make Ajax requests to the server and update the search results in real-time. You can include Vanilla JavaScript in your index.html file by adding the following code:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ajax Live Data Search 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-primary text-center"><b>Ajax Live Data Search in Node.js with MySql</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Customer Data</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input type="text" id="search" placeholder="Search..." class="form-control" autocomplete="off">
                        <table class="table table-bordered mt-3">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody id="results">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">

const searchInput = document.querySelector('#search');

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

load_data();

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

    request.open('GET', `/search?q=${query}`);

    request.onload = () => {

        const results = JSON.parse(request.responseText);

        let html = '';

        if(results.length > 0)
        {
            results.forEach(result => {
                html += `
                <tr>
                    <td>`+result.customer_id+`</td>
                    <td>`+result.customer_first_name+`</td>
                    <td>`+result.customer_last_name+`</td>
                    <td>`+result.customer_email+`</td>
                    <td>`+result.customer_gender+`</td>
                </tr>
                `;
            });
        }
        else
        {
            html += `
            <tr>
                <td colspan="5" class="text-center">No Data Found</td>
            </tr>
            `;
        }

        results_body.innerHTML = html;

    };

    request.send();
}

searchInput.addEventListener('input', () => {

    const query = searchInput.value;

    load_data(query);

});

</script>


This code listens for keyup events on the search input field and makes an Ajax request to the server with the search query. The server responds with a JSON object containing the search results, which are then displayed in the search results list.

To handle the Ajax requests on the server, add the following code to "app.js":

app.js

app.get('/search', (request, response) => {

	const query = request.query.q;

	var sql = '';

	if(query != '')
	{
		sql = `SELECT * FROM customers WHERE customer_first_name LIKE '%${query}%' OR customer_last_name LIKE '%${query}%' OR customer_email LIKE '%${query}%'`;
	}
	else
	{
		sql = `SELECT * FROM customers ORDER BY customer_id`;
	}

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

		if (error) throw error;

		response.send(results);

	});

});


This code creates a MySQL connection and listens for GET requests to "/search". It retrieves the search query from the GET request URL and executes a SQL query to search for customers whose first name, last name or email matches the query. The results are returned as a JSON object.

Step 4: Run Node Application


So here our code is ready now for check output in the browser, we have goes to terminal and run following command.


node app.js


This command will start node server and we can access this node application in browser by this http://localhost:3000 url.

Conclusion


In this article, we have shown you how to implement an Ajax live search feature using Node.js and MySQL. By using these technologies, you can build responsive and efficient web applications that provide a great user experience. With a few lines of code, you can easily add this feature to your web application and improve its functionality.

Complete Source Code


app.js



const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000;

const pool = mysql.createPool({
	connectionLimit : 10,
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

app.get('/', (request, response) => {

	response.sendFile(__dirname + '/index.html');

});

app.get('/search', (request, response) => {

	const query = request.query.q;

	var sql = '';

	if(query != '')
	{
		sql = `SELECT * FROM customers WHERE customer_first_name LIKE '%${query}%' OR customer_last_name LIKE '%${query}%' OR customer_email LIKE '%${query}%'`;
	}
	else
	{
		sql = `SELECT * FROM customers ORDER BY customer_id`;
	}

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

		if (error) throw error;

		response.send(results);

	});

});

app.listen(port, () => {

	console.log(`Server listening on port ${port}`);

});


index.html



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ajax Live Data Search 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-primary text-center"><b>Ajax Live Data Search in Node.js with MySql</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Customer Data</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input type="text" id="search" placeholder="Search..." class="form-control" autocomplete="off">
                        <table class="table table-bordered mt-3">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody id="results">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">

const searchInput = document.querySelector('#search');

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

load_data();

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

    request.open('GET', `/search?q=${query}`);

    request.onload = () => {

        const results = JSON.parse(request.responseText);

        let html = '';

        if(results.length > 0)
        {
            results.forEach(result => {
                html += `
                <tr>
                    <td>`+result.customer_id+`</td>
                    <td>`+result.customer_first_name+`</td>
                    <td>`+result.customer_last_name+`</td>
                    <td>`+result.customer_email+`</td>
                    <td>`+result.customer_gender+`</td>
                </tr>
                `;
            });
        }
        else
        {
            html += `
            <tr>
                <td colspan="5" class="text-center">No Data Found</td>
            </tr>
            `;
        }

        results_body.innerHTML = html;

    };

    request.send();
}

searchInput.addEventListener('input', () => {

    const query = searchInput.value;

    load_data(query);

});

</script>



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: Ajax Live Search using Node.js with MySQL
Ajax Live Search using Node.js with MySQL
https://i.ytimg.com/vi/ixz2odtavvs/hqdefault.jpg
https://i.ytimg.com/vi/ixz2odtavvs/default.jpg
kumpulan driver
https://kepsuk.blogspot.com/2023/03/ajax-live-search-using-nodejs-with-mysql_14.html
https://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/2023/03/ajax-live-search-using-nodejs-with-mysql_14.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