Menu

What are Ajax calls?

By Aravindan Chandrasekaran | Open Web

Feb 28

 

AJAX – Asynchronous JavaScript And XML is broadly used for communicating with server using javascript. AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. In this post, lets look at how to acheive AJAX with Node/Express.js. 

AJAX, An Introduction

Welcome to the part three of Node.js learning series. This post is all about AJAX and how to implement AJAX with Node.js/Express.js. AJAX is not a programming language, but it is more of a methodology. The main purpose of AJAX is to create a simple means of communication between the client web application and the server and update the client’s DOM with the new data without reloading the entire web page, if that can be avoided.

Best way to experience AJAX is Facebook. When you open your Facebook wall, only a few posts are loaded initially. As you scroll down, more posts are fetched from the server and presented to you on the fly, providing a limitless, infinite source of content and updates from your friends.

An AJAX request from client to server is achieved in a way which is compatible with the standard protocol used for retrieving webpages when the browser first sends the request to load a website. Yes, thats HTTP, the Hyper Text Transfer Protocol. HTTP works on the concept of methods  and we are going to use a few of them to make AJAX calls.

Two HTTP Request Methods : GET and POST

Two commonly used methods for a request-response transaction between a client and server are: GET and POST.

  • GET – Requests data from a specified resource in server
  • POST – Submits data to be processed by a specified resource in server

GET request

Handling GET request in Express is easy, and we saw that in the last post.

app.get('/', function (req, res) {
      res.send('Hello World!')
})

POST request

Express 4 requires extra middleware layer to handle POST requests. This middleware is called as ‘bodyParser’. This used to be internal part of Express framework but now you have to install it separately.

sudo npm install body-parser --save

Require the body-parser middleware in Express app and use it like this within the main app.js file of your Express application directory.

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

AJAX Demo with Node/Express

User Login Page

Let us see a demo to understand how to use GET requests to load the login page and use POST request to send the user name and password to the server. We will keep it very simple and so, we are not going to use any database for storing the user credentials.

So let’s get started. The complete source code for this demo is available in this GitHub repo.

In the client side html, we’ll use the AJAX post call within the form, to send the login credentials to the server on click of submit button.

As we learned in the previous post, we’ll use the Express Router here for defining all routes inside the app. So when a request from client hits the server, the server responds with the response html file, like this.

router.get('/', function(req, res) {
      res.send('index.html');
});

Ajax-Simple-login

In case of our user login AJAX demo, when user types in the login credentials and clicks submit, a POST request is made to the server. This will contain the username and password as data within the POST method.

router.post('/login',function(req,res){
    var user_name=req.body.username;
    var password=req.body.pwd;
    console.log("User name is : "+user_name+", password is :"+password);
    if(user_name === 'user' && password === 'password'){
        res.send("authorized");
    }else{
        res.send("Unauthorized");
    }
});

 

The bodyparser module, imported in the main app.js file is used to get the data from POST request and stored in ‘user_name’ and ‘password’ variable. Subsequently, they are matched against the constant strings in the if condition inside the route.
Based on the logic defined inside the route, the server responds to the user request with correct and incorrect credentials as shown in pictures below.
Ajax-login-authorized

Ajax-login-unauthorized

Summary

This post would have provided you with a clear picture of how an AJAX GET and POST call works. In our next post of this series, we will create a simple Express application with databases, to add some realistic flair to our demos.

Follow

About the Author

Aravind is a technology enthusiast. He is an expert in conceptualizing and developing niche apps around IoT and cloud computing and is aspiring to be a full stack developer.

>