Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view example

Integrate-node.js-express-with-ajax-post-get-api

In the tutorial, we show how to integrate NodeJS/Express with JQuery Ajax POST/GET requests and Bootstrap view.

Related posts:
How to build NodeJS/Express Bootstrap views
NodeJS/Express – save form data to MySQL using Sequelize ORM – Ajax JQuery + Bootstrap view

Goal

We create a NodeJS/Express project as below structure:


/nodejs-express-jquery-ajax-bootstrap
	/node_modules
	/public
		/js
			getrequest.js
			postrequest.js
	/views
		404.html
		index.html
	app.js
	package.json

Run above NodeJS/Express application then does POST/GET requests:

NodeJs-Express-JQuery-Ajax-Post-Get-with-Bootstrap-View

Practice

Setting up NodeJS/Express project

Create folder: nodejs-express-bootstrap and init nodejs application.


mkdir nodejs-express-jquery-ajax-bootstrap
cd nodejs-express-jquery-ajax-bootstrap

See prompts:


nodejs-express-jquery-ajax-bootstrap>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-ajax-bootstrap)
version: (1.0.0)
description: Integrate NodeJS Express with JQuery Ajax Post/Get requests and Bootstrap view
entry point: (index.js) app.js
test command:
git repository:
keywords: NodeJs, Express, Bootstrap, Jquery, Ajax
author: grokonez.com
license: (ISC)
About to write to C:\Users\pc\Desktop\nodejs\nodejs-express-jquery-ajax-bootstrap\package.json:

{
  "name": "nodejs-express-jquery-ajax-bootstrap",
  "version": "1.0.0",
  "description": "Integrate NodeJS Express with JQuery Ajax Post/Get requests and Bootstrap view",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJs",
    "Express",
    "Bootstrap",
    "Jquery",
    "Ajax"
  ],
  "author": "grokonez.com",
  "license": "ISC"
}


Is this ok? (yes) yes

Now we have an package.json file in folder nodejs-express-jquery-ajax-bootstrap with content as below:


{
  "name": "nodejs-express-jquery-ajax-bootstrap",
  "version": "1.0.0",
  "description": "Integrate NodeJS Express with JQuery Ajax Post/Get requests and Bootstrap view",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJs",
    "Express",
    "Bootstrap",
    "Jquery",
    "Ajax"
  ],
  "author": "grokonez.com",
  "license": "ISC"
}

Installing Express


$npm install express --save

-> Check package.json file:


{
  "name": "nodejs-express-jquery-ajax-bootstrap",
  "version": "1.0.0",
  "description": "Integrate NodeJS Express with JQuery Ajax Post/Get requests and Bootstrap view",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJs",
    "Express",
    "Bootstrap",
    "Jquery",
    "Ajax"
  ],
  "author": "grokonez.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3"
  }
}

Implement Bootstrap views

./views/index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Spring Boot - AJAX POST GET Example</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="/js/getrequest.js"></script>
  <script src="/js/postrequest.js"></script>
</head>

<body> 
<div class="container"> 
<div class="col-sm-4">
	<h3>NodeJS/Express Post/Get Ajax</h3>
	<div>		
		<form id="customerForm">
		  <div class="form-group">
			<label for="firstname">FirstName:</label>
			<input type="text" class="form-control" id="firstname" placeholder="Enter FirstName"/>
		  </div>
		  <div class="form-group">
			<label for="lastname">LastName:</label>
			<input type="text" class="form-control" id="lastname" placeholder="Enter LastName"/>
		  </div>
		  <button type="submit" class="btn btn-default">Submit</button>
		</form>
	</div>
	<div id="postResultDiv">
	</div>
	<br>
	<div>
		<button id="allCustomers" type="button" class="btn btn-default">Customers</button>
		<div id="getResultDiv">
	        <ul class="list-group">
	    	</ul>
    	</div>
	</div>
</div>	
</div>
</body>
</html>

./views/404.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</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 Ajax requests

– For JQuery Ajax POST request, we implement a ./public/js/postrequest.js file:


$( document ).ready(function() {
	
	// SUBMIT FORM
    $("#customerForm").submit(function(event) {
		// Prevent the form from submitting via the browser.
		event.preventDefault();
		ajaxPost();
	});
    
    
    function ajaxPost(){
    	
    	// PREPARE FORM DATA
    	var formData = {
    		firstname : $("#firstname").val(),
    		lastname :  $("#lastname").val()
    	}
    	
    	// DO POST
    	$.ajax({
			type : "POST",
			contentType : "application/json",
			url : window.location + "api/customers/save",
			data : JSON.stringify(formData),
			dataType : 'json',
			success : function(customer) {
				$("#postResultDiv").html("

" + "Post Successfully!
" + "--->" + JSON.stringify(customer)+ "

"); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#firstname").val(""); $("#lastname").val(""); } })

– For JQuery Ajax Get request, we implement a ./public/js/getrequest.js file:


$( document ).ready(function() {
	
	// GET REQUEST
	$("#allCustomers").click(function(event){
		event.preventDefault();
		ajaxGet();
	});
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : window.location + "api/customers/all",
			success: function(result){
				$('#getResultDiv ul').empty();
				var custList = "";
				$.each(result, function(i, customer){
					$('#getResultDiv .list-group').append(customer.firstname + " " + customer.lastname + "
") }); console.log("Success: ", result); }, error : function(e) { $("#getResultDiv").html("Error"); console.log("ERROR: ", e); } }); } })

Implement Express Routes

In main NodeJS app.js file, we implement Express routes:


var express = require("express");
var app = express();

var router = express.Router();
var bodyParser = require('body-parser');
app.use(bodyParser.json());

app.use(express.static('public'));

var path = __dirname + '/views/';

var customers = [];

router.use(function (req,res,next) {
  console.log("/" + req.method);
  next();
});

app.get("/",function(req,res){
  res.sendFile(path + "index.html");
});

app.post("/api/customers/save", function(req,res){
	console.log('Post a Customer: ' + JSON.stringify(req.body));
	var customer = {};
	customer.firstname = req.body.firstname;
	customer.lastname = req.body.lastname;
	
	customers.push(customer);
	
	return res.send(customer);
});

app.get("/api/customers/all", function(req,res){
	console.log("Get All Customers");
	return res.send(customers);
});

app.use("/",router);

app.use("*",function(req,res){
  res.sendFile(path + "404.html");
});

app.listen(8081, function () {
  console.log('Example app listening on port 8081!')
})

Run & Check results

Run NodeJS application then makes requests:
->Server’s Logs:


>node app.js
Example app listening on port 8081!
/GET
/GET
Post a Customer: {"firstname":"Jack","lastname":"Davis"}
Post a Customer: {"firstname":"Mary","lastname":"Taylor"}
Post a Customer: {"firstname":"Peter","lastname":"Thomas"}
Post a Customer: {"firstname":"Amos","lastname":"Nelson"}
Post a Customer: {"firstname":"Craig","lastname":"White"}
Post a Customer: {"firstname":"Laura","lastname":"Lewis"}
Post a Customer: {"firstname":"Steven","lastname":"Harris"}
Post a Customer: {"firstname":"Paul","lastname":"Moore"}
Post a Customer: {"firstname":"Mary","lastname":"Cook"}
Get All Customers

NodeJs-Express-JQuery-Ajax-Post-Get-with-Bootstrap-View-request

NodeJs-Express-JQuery-Ajax-Post-Get-with-Bootstrap-View

Sourcecode

Nodejs-Express-JQuery-Ajax-Bootstrap



By grokonez | May 3, 2018.

Last updated on April 30, 2021.



Related Posts


5 thoughts on “Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view example”

  1. Could you please explain the routing i.e. “api/customers/save” and “api/customers/all”?
    If I try to change to change the route for post request to “api/customers/submit” in both the app.js file and postrequest.js file…it shows an error, what is the reason for this?

  2. Hello grokonez ,
    Thanks for the Good explanation on this interesting topic, unfortunately This program is not working for me.
    When I hit the SUBMIT button it is not showing the message “Post Successfully!”, but I am able to see the function “ajaxPost” in the browser inspect/debugmode, I tried to put a breakpoint and it is not reaching the breakpoint.
    It seems like the “ajaxPost” method is not firing when SUBMIT button is pressed.

    Please let me know if I am missing any.

    Thanks,
    Naga.

  3. Would it be hard to show an example of using handlebars (.hbs) template system? I get 404 errors trying to get it to read the post and get paths because it uses an app.js and an index.js. Putting your app.js code in mine doesn’t seem to work.

Got Something To Say:

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

*