NodeJS/Express + Bootstrap Filter Table + JQuery example

In the tutorial, we show how to implement Bootstrap Filter Table with JQuery and NodeJS/Express RestAPIs.

Related posts:
NodeJs/Express RestAPIs – POST/GET/PUT/DELETE requests
NodeJS/Express Rest APIs + Bootstrap Table + Ajax JQuery

Goal

Bootstrap does NOT support a typical component for filtering. So we can use JQuery to filter elements:


$("#inputFilter").on("keyup", function() {
    var inputValue = $(this).val().toLowerCase();
    $("#customerTable tr").filter(function() {
    	$(this).toggle($(this).text().toLowerCase().indexOf(inputValue) > -1)
    });
});

We create a NodeJS/Express project as below structure:


/NodeJS-Express-JQuery-Bootstrap-Filter-Tables
	/app
		/controllers
			customer.controller.js
		/routes
			customer.route.js
	/node_modules
	/resources
		/static
			/js
				jquery-filter-table.js
	/views
		404.html
		index.html
	package.json
	package-lock.json
	server.js

Run above project then makes a request http://localhost:8081

-> Bootstrap view:

NodeJS-Express-Bootstrap-Filter-Table-JQuery-all customers

-> Filter table:

NodeJS-Express-Bootstrap-Filter-Table-JQuery-filter

Practice

Setting up NodeJS/Express project

Create a folder ‘NodeJS-Express-JQuery-Bootstrap-Filter-Tables’:


mkdir NodeJS-Express-JQuery-Bootstrap-Filter-Tables
cd NodeJS-Express-JQuery-Bootstrap-Filter-Tables

Then init NodeJS project, see prompts:


NodeJS-Express-JQuery-Bootstrap-Filter-Tables>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs-express-jquery-bootstrap-filter-tables)
version: (1.0.0)
description: Bootstrap Filter Tables with JQuery + NodeJS/EXpress
entry point: (index.js) server.js
test command:
git repository:
keywords: NodeJS, Express, Bootstrap-Filter-Table, JQuery
author: grokonez.com
license: (ISC)
About to write to C:\Users\pc\Desktop\nodejs\NodeJS-Express-JQuery-Bootstrap-Filter-Tables\package.json:

{
  "name": "nodejs-express-jquery-bootstrap-filter-tables",
  "version": "1.0.0",
  "description": "Bootstrap Filter Tables with JQuery + NodeJS/EXpress",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Bootstrap-Filter-Table",
    "JQuery"
  ],
  "author": "grokonez.com",
  "license": "ISC"
}


Is this ok? (yes) yes

-> Install Express:


npm install express body-parser --save

-> see package.json file:


{
  "name": "nodejs-express-jquery-bootstrap-filter-tables",
  "version": "1.0.0",
  "description": "Bootstrap Filter Tables with JQuery + NodeJS/EXpress",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Bootstrap-Filter-Table",
    "JQuery"
  ],
  "author": "grokonez.com",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3"
  }
}

Frontend

Create Bootstrap views

./views/index.html file:

<!DOCTYPE HTML>
 
<html>
<head>
      <title>Bootstrap Filter Table + NodeJS/Express</title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
	  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	  <script src="/static/js/jqueryAjax.js"></script>
</head>
 
<body>
<div class="container">
		<h2>Bootstrap Filter Table</h2>
		<div class="row col-md-7 ">
			<div style="margin-bottom:20px; padding:10px; background-color:#336699; color:white;">
		  	<p>Type some text to search the table for <strong>Id</strong>, <strong>Name</strong>, <strong>Age</strong>, <strong>Street</strong>, <strong>PostCode</strong>:</p>  
		  	<input class="form-control" id="inputFilter" type="text" placeholder="Search.." />
		  	</div>
			<table id="customerTable" class="table table-bordered table-hover table-responsive">
				<thead>
					<tr>
						<th>Id</th>
						<th>Name</th>
						<th>Age</th>
						<th>Street</th>
						<th>Postcode</th>
					</tr>
				</thead>
				<tbody>
				</tbody>
			</table>
		</div>
	</div>
	
</body>
</html>

./views/404.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>404 Error!</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  
<div class="jumbotron text-center">
  <h1>404 Error!</h1>
  <p>PAGE NOT FOUND</p>
</div>
</body>
</html>

Implement Jquery scripts

– For loading data and filter data, we implement a file ./resources/static/js/jquery-filter-table.js:


$(document).ready(function() {
	
	// DO GET
	$.ajax({
		type : "GET",
		url : "api/customers/all",
		success: function(result){
			$.each(result, function(i, customer){
				
				var customerRow = '' +
									'' + customer.id + '' +
									'' + customer.name.toUpperCase() + '' +
									'' + customer.age + '' +
									'' + customer.address.street + '' +
									'' + customer.address.postcode + '' +
								  '';
				
				$('#customerTable tbody').append(customerRow);
				
	        });
			
			$( "#customerTable tbody tr:odd" ).addClass("info");
			$( "#customerTable tbody tr:even" ).addClass("success");
		},
		error : function(e) {
			alert("ERROR: ", e);
			console.log("ERROR: ", e);
		}
	});
	
	// do Filter on View
	$("#inputFilter").on("keyup", function() {
	    var inputValue = $(this).val().toLowerCase();
	    $("#customerTable tr").filter(function() {
	    	$(this).toggle($(this).text().toLowerCase().indexOf(inputValue) > -1)
	    });
	});
})

Backend

Create Express Routes

./app/routes/customer.route.js file:


module.exports = function(app) {
 
	var express = require("express");
	var router = express.Router();
	
    const customers = require('../controllers/customer.controller.js');
	
	var path = __basedir + '/views/';
	
	router.use(function (req,res,next) {
		console.log("/" + req.method);
		next();
	});
	
	app.get('/', (req,res) => {
		res.sendFile(path + "index.html");
	});
 
    // Retrieve all Customers
    app.get('/api/customers/all', customers.getAll);
	
	app.use("/",router);
 
	app.use("*", (req,res) => {
		res.sendFile(path + "404.html");
	});
}

Implement Controllers

./app/controllers/customer.controller.js file:


// Fetch all Customers
var customers = [
					{
						id: 1,
						name: "Jack",
						age: 25,
						address:{
							street: "NANTERRE CT",
							postcode: "77471"
						}
					},
					{
						id: 2,
						name: "Mary",
						age: 37,
						address:{
							street: "W NORMA ST",
							postcode: "77009"
						}
					},
					{
						id: 3,
						name: "Peter",
						age: 17,
						address:{
							street: "S NUGENT AVE",
							postcode: "77571"
						}
					},
					{
						id: 4,
						name: "Amos",
						age: 23,
						address:{
							street: "E NAVAHO TRL",
							postcode: "77449"
						}
					},
					{
						id: 5,
						name: "Craig",
						age: 45,
						address: {
							street: "AVE N",
							postcode: "77587"
						}
					},
					{
						id: 6,
						name: "Aries",
						age: 19,
						address: {
							street: "Broadway/Reade St, New York",
							postcode: "10007"
						}
					},
					{
						id: 7,
						name: "Brice",
						age: 39,
						address: {
							street: "Columbus, OH 43215, USA",
							postcode: "43215"
						}
					},
					{
						id: 8,
						name: "Cage",
						age: 24,
						address: {
							street: "Plano, TX 75074",
							postcode: "75074"
						}
					},
					{
						id: 9,
						name: "Ellen",
						age: 41,
						address: {
							street: "Modesto, CA 95354",
							postcode: "95354"
						}
					},
					{
						id: 10,
						name: "Brice",
						age: 32,
						address: {
							street: "Atlanta, GA 30334",
							postcode: "30334"
						}
					}
			]
			
exports.getAll = (req, res) => {
	console.log("--->Get All Customers: \n" + JSON.stringify(customers, null, 4));
    res.send(customers); 
};

Implement Server.js

./server.js file:


var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())
 
app.use(express.static('resources'));
global.__basedir = __dirname;
 
require('./app/routes/customer.route.js')(app);
 
// Create a Server
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port) 
})

Run & Check results

Start NodeJS server, then makes a request: http://localhost:8081
-> Logs:


NodeJS-Express-JQuery-Bootstrap-Filter-Tables>node server.js
App listening at http://:::8081
--->Get All Customers:
[
    {
        "id": 1,
        "name": "Jack",
        "age": 25,
        "address": {
            "street": "NANTERRE CT",
            "postcode": "77471"
        }
    },
    {
        "id": 2,
        "name": "Mary",
        "age": 37,
        "address": {
            "street": "W NORMA ST",
            "postcode": "77009"
        }
    },
    {
        "id": 3,
        "name": "Peter",
        "age": 17,
        "address": {
            "street": "S NUGENT AVE",
            "postcode": "77571"
        }
    },
    {
        "id": 4,
        "name": "Amos",
        "age": 23,
        "address": {
            "street": "E NAVAHO TRL",
            "postcode": "77449"
        }
    },
    {
        "id": 5,
        "name": "Craig",
        "age": 45,
        "address": {
            "street": "AVE N",
            "postcode": "77587"
        }
    },
    {
        "id": 6,
        "name": "Aries",
        "age": 19,
        "address": {
            "street": "Broadway/Reade St, New York",
            "postcode": "10007"
        }
    },
    {
        "id": 7,
        "name": "Brice",
        "age": 39,
        "address": {
            "street": "Columbus, OH 43215, USA",
            "postcode": "43215"
        }
    },
    {
        "id": 8,
        "name": "Cage",
        "age": 24,
        "address": {
            "street": "Plano, TX 75074",
            "postcode": "75074"
        }
    },
    {
        "id": 9,
        "name": "Ellen",
        "age": 41,
        "address": {
            "street": "Modesto, CA 95354",
            "postcode": "95354"
        }
    },
    {
        "id": 10,
        "name": "Brice",
        "age": 32,
        "address": {
            "street": "Atlanta, GA 30334",
            "postcode": "30334"
        }
    }
]

-> Browser Network’s Logs:

NodeJS-Express-Bootstrap-Filter-Table-JQuery-browser-network-loging

-> Bootstrap views:

NodeJS-Express-Bootstrap-Filter-Table-JQuery-all customers

-> Filter:

NodeJS-Express-Bootstrap-Filter-Table-JQuery-filter

Sourcecode

To run below sourcecode, follow the guides:

step 0: download & extract zip file -> we have a folder ‘NodeJS-Express-JQuery-Bootstrap-Filter-Tables’
step 1: cd NodeJS-Express-JQuery-Bootstrap-Filter-Tables
step 2: npm install express body-parser –save
step 3: node server.js

-> Sourcecode:

NodeJS-Express-JQuery-Bootstrap-Filter-Tables



By grokonez | May 10, 2018.

Last updated on April 10, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*