Share
Explore

Ajax as the communication between the front end web page and the back end Node.js controller program.

Learning Outcome: Write a NodeJS application in which you make a web application with a front end BUTTON in the HTML page which runs a Node.js program in the back end.
There are 2 fields and a button on the html page. The data from the fields is transacted to the node.js backend program which adds the numbers and returns the result.
jQuery is used in the HTML page to change the page color based on the result.

Welcome to this Node.js Student Lab Learning Workbook! In this workbook, we'll go through the process of creating a simple web application. This application will feature an HTML page with two input fields and a button. When the button is clicked, the data from the fields will be sent to a Node.js server, which will add the numbers together and return the result. Furthermore, we'll use jQuery on the HTML page to change the page's color based on the result.
Before we begin, make sure you have Node.js and npm (Node Package Manager) installed on your computer. If you haven't installed them yet, you can download them from the .

Table of Contents

Setting Up Your Node.js Server
Creating Your HTML Page
Setting Up jQuery
Connecting Your Frontend and Backend
Additional Exercises



Node.js Web Application Workbook

Introduction

In this workbook, we will learn how to create a simple web application using Node.js. The application will have a front-end HTML page with two input fields and a button. When the button is clicked, the data from the two fields will be sent to a Node.js backend server which will add the numbers and return the result. We will use jQuery to change the color of the HTML page based on the result.
Let's get started!

Prerequisites

Basic knowledge of HTML, JavaScript, and jQuery.
Node.js and npm (Node Package Manager) installed on your computer. If not, you can download and install from
.
A text editor, such as Visual Studio Code.

Step 1: Set up the Project

Create a new directory for your project and navigate into it:
bashCopy code
mkdir node-web-app
cd node-web-app

Initialize a new Node.js project. When you run the initialization command, npm will ask you some questions. Feel free to press enter to accept the defaults.
bashCopy code
npm init -y

Step 2: Install Express

We'll use Express, a popular Node.js web framework, to create our server. Install it using npm:
bashCopy code
npm install express

Step 3: Create the Server

Create a new file named server.js in your project directory and add the following code:
javascriptCopy code
const express = require('express');
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});

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

This code sets up an Express server that listens on port 3000 and serves an HTML file located in the same directory when the root URL (/) is accessed.

Step 4: Create the Frontend

Create a new file named index.html in your project directory and add the following HTML code:

<!DOCTYPE html>
<html>
<head>
<title>Node.js Web App</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<button id="calculate">Add</button>
<div id="result"></div>

<script src="app.js"></script>
</body>
</html>

This HTML file has two input fields, a button, and a div to display the result【8†source】.

Step 5: Create the Frontend JavaScript

Create a new file named app.js in your project directory and add the following JavaScript code:

$(document).ready(function() {
$('#calculate').click(function() {
const num1 = $('#num1').val();
const num2 = $('#num2').val();
$.ajax({
url: '/add',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ num1, num2 }),
success: function(response) {
$('#result').text('Result: ' + response.result);
$('body').css('background-color', response.color);
}
});
});
});

This jQuery code waits for the button click, retrieves the values from the input fields, and sends a POST request to the '/add## Step 6: Create the Backend API
Now, we need to create an API endpoint in our Node.js server to receive the numbers from the front end, add them, and send back the result.
Step 6.1: In server.js, add a new POST route /add:

app.post('/add', (req, res) => {
const { number1, number2 } = req.body;
const sum = Number(number1) + Number(number2);
const color = sum > 10 ? 'green' : 'red';
res.json({ result: sum, color: color });
});

In this route, we're retrieving the numbers from the request body, adding them, and determining a color based on the sum (green if the sum is greater than 10, red otherwise). Then we're sending back a JSON response with the sum and the color.

Step 7: Test Your Application

To test your application, start your Node.js server:
shellCopy code
node server.js

Then, open your browser and visit http://localhost:3000. Try entering different numbers in the input fields and clicking the button. You should see the sum of the numbers displayed, and the page's background color should change based on the sum.

Conclusion

Congratulations! You've just built a simple web application with a Node.js backend and a jQuery frontend. This application receives data from the user, sends it to the server, processes it, and updates the page based on the server's response.

Additional Exercises

To further practice your skills, try modifying your application to perform different operations (like subtraction, multiplication, or division), change the color scheme, or add additional input fields and server routes. The possibilities are endless!
Remember, the key to learning is practice. Don't be afraid to experiment and make mistakes. Happy coding!

Summarize how AJAX is used to communicate between front end html page and back end node.js server program


AJAX, which stands for Asynchronous JavaScript and XML, is a set of web development techniques used to send and retrieve data from a server asynchronously, without interfering with the display and behavior of the existing page.
In the context of the Node.js web application we created, AJAX is used to facilitate the communication between the front end HTML page and the back end Node.js server program.
Here's a summary of the steps involved:
Event Trigger: The process begins when the user clicks the "Add" button on the HTML page. This triggers a jQuery click event handler.
AJAX Request: Inside the click event handler, an AJAX request is made to the server. The $.ajax() function is used to create this request. This function takes an object as its argument, which contains information about the request:
url: This is the route on the server that the request will be sent to (in this case, '/add').
method: This is the HTTP method to be used for the request (in this case, 'POST').
contentType: This is the type of content being sent to the server (in this case, 'application/json').
data: This is the actual data being sent to the server. It's converted into a JSON string before being sent.
Server Processing: On the server side, the Node.js application receives the AJAX request at the '/add' route. It extracts the data from the request, performs the required operation (in this case, adding the numbers), and determines a color based on the result.
Response: The server then sends back a response. This response is a JSON object containing the result of the operation and the determined color.
Updating the HTML Page: Back on the front end, the success callback function in the $.ajax() call is triggered when the response from the server is received. This function updates the text of the #result element with the received sum, and changes the background color of the page based on the received color.
In summary, AJAX allows the front end and the back end of the web application to communicate with each other in real time, without the need for a page reload. The front end sends a request to the server with user data, the server processes this data and sends back a response, and the front end updates the page based on this response.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.