Ajax Search Box Using Node and MySQL

Ajax search is one of must have feature in any application. It allow user’s to search for any doubt, and will show suggestion based on their input. Just like how Google do or Facebook graph search, although they are very advanced search box.

In this tutorial, i am going to develop an Ajax Search Box using Node and MySQL as database. For front-end i am going to use Bootstrap and Typeahead library.

Our approach is to call our Node server for every key input, fetch data from database, pack the response in JSON format and return it to client. In client-end we will extract those JSON response and show it to Search box immediately.

What is Typeahead.js ?

Twitter develop this JavaScript library for efficient web development. By using this library one can simply create an Ajax Search box. You can use this to search for your local data or remote data as well.

It is simple to use, we have to import the script, and by using JavaScript selector or JQuery selector we can initialize and invoke the typeahead.

Database design:

Create any database in MySQL and paste following query to create table inside that database.

CREATE TABLE 'user_name'
user_id INT(20) PRIMARY KEY,
first_name TEXT

Put some dummy data in that using INSERT command.

"name": "Ajax-Search-Box",
"version": "1.0.1",
"dependencies": {
"express": "~4.6.1",
"ejs": "~1.0.0",
"mysql": "~2.4.1"

You can install this dependencies by

npm install

You may need sudo access in Linux or Mac based System.

Directory Structure:

Here is a Project directory structure.


HTML and JS Code

We are using typeahead.js library to enable Ajax search feature. So we have to include them in our HTML file as well.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">script>
<script src="typeahead.min.js" type="text/javascript">script>

We will initialize the typeahead in JQuery function. Here have a look.

name: 'typeahead',
remote: 'http://localhost:3000/search?key=%QUERY',
limit: 10

We are calling the remote URL by passing the input keyword provided by user. Here is HTML part of Search box.

<input class="typeahead tt-query" spellcheck="false" autocomplete="off" name="typeahead" type="text" />

This file contains code for loading Server, handling request, handling Database operations and returning response for a valid request.
Our first job is to load the dependencies we want to use.

var express=require('express');
var app=express();
var mysql=require('mysql');

Next job is to define the application configuration. We are using ‘view’ folder for storing front end code and JS folder for JavaScript library so we have to tell express to do so by using following code.

app.set('views',__dirname + '/views');
app.use(express.static(__dirname + '/JS'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

Next, we will connect to our MySQL database. This is a code to do so.

var connection = mysql.createConnection({
host : 'Host name; localhost for local',
user : 'User name ; root mostly',
password : 'password of MySQL; blank mostly',
database : 'Your database name'

Once we are connected to database, our job is to handle router. Router defines the working of app in different scenario. We are using two routers here, one to deliver home page of app, second to extract key of search and returning result.

//Return home page
//Extract the keyword.
//Return the result depending on the keyword.
//extract key using req.query.key
//call MySQL Query.
//form JSON response and return.

Depending upon your database design your MySQL query may be different than mine. Here is a complete router code.


connection.query('SELECT first_name from TABLE_NAME where first_name like "%'+req.query.key+'%"',
function(err, rows, fields) {
if (err) throw err;
var data=[];

Next task is to start our app.

var server=app.listen(3000,function(){
console.log("We have started our server on port 3000");

You can use any type of CSS you want to design your front-end, it is not specific so i am not posting it here. You can download the code from Github and run it at your end.

How to run the app:

Download the source code from Github. Change the MySQL configuration. Run the app by typing

node Server.js

in prompt. Visit localhost:3000 to view the app.

13 thoughts on “Ajax Search Box Using Node and MySQL”

  1. Hi, i’v been looking for this and thanks to you, i customize it like i wanted and it work very well!!!!! thanks again!!!

  2. Thank you for this example. It works great with one data set i get remotely from mysql. How to handle multiple data sets?

    1. I would like to have multiple search boxes like City, Country and State and each one remotely getting data from mysql

  3. How to use “escape” method in this program to sanitize out input data ?
    the following code adding extra single quotes to the string .
    How can i fix it ?

  4. Hi I am able to fetch the data on search.php in json but how do i get it on my front end page which is index.html ? Thank you. Rest of your code works like a charm.

  5. Thank you so much Sir…I recently got a job and your post really helping me out of this…
    One questions
    Can you please show me the way of selecting a city name(Bangalore) from a cities table and showing all the towns if that particular city.

  6. Hi am able to store that selected element as ‘ hello’ into other table using angularjs ng-model and nodejs and mysql.when am saving selected element it giving as entering first elemnet not the selected one. What i have to write at place of n-model.

  7. Hi am able to store that selected element as ‘ hello’ into other table using angularjs ng-model and nodejs and mysql.when am saving selected element it giving as entering first elemnet not the selected one. What i have to write at place of ng-model.

  8. Hi, Can I return the content in the response to another view by the method render?
    Thank you in advance

  9. Hi… Thank you for this post. It works great. I just wanted to check with you if you were able to bold the typed items in the suggession list

Comments are closed.