AJAX

AJAX

Published by: Anil K. Panta

AJAX

Ajax stands for Asynchronous JavaScript and XML. It is used to make asynchronous communication with the server. Ajax is used to read data from the server and update the page or send data to the server without affecting the current client page. Ajax is a programming concept. 

Below are some ways to make Ajax calls in JavaScript.


  • Using the XMLHttpRequest object

  • Using jQuery

  • Using fetch() API


We will explore all the above methods along with their basic implementation with the help of examples.



Using the XMLHttpRequest object

In this approach, we will use the XMLHttpRequest object to make an Ajax call. The XMLHttpRequest() method creates an XMLHttpRequest object which is used to make a request with the server.  

Syntax

let xhttp = new XMLHttpRequest();

Above syntax is used to create an XMLHttpRequest object. This object has many different methods used to interact with the server to send, receive or interrupt responses from the server. In the response, we get a string from the server that we print. 

Example: 

In this example, we will use the XMLHttpRequest object to make an Ajax call.


Output

"{

 "userId": 1,

 "id": 1,

 "title": "delectus aut autem",

 "completed": false

}"


Using jQuery

In this approach, we will use jQuery to make an Ajax call. The ajax() method is used in jQuery to make ajax calls. It is used as a replacement for all approaches which are not working to make ajax calls. 


Syntax:

$.ajax({arg1: value, arg2: value, ... });

Parameter: It takes a configuration file that configures the URL, type, and function to call when we get our response or if error, etc.


Example:  

In this example, we will use jQuery to make an ajax call.



Output

{

 "userId": 1,

 "id": 1,

 "title": "delectus aut autem",

 "completed": false

}


Using fetch() API

In this approach, we will use fetch() API which is used to make XMLHttpRequest with the server. Because of its flexible structure, it is easy to use. This API makes a request to the server and gets the result as a promise which is resolved to the string.


Syntax

fetch(url, {config}).then().catch();

Parameter: It takes URL and config of the request as parameters. 

We will configure the data required and make the request to the server. Since it is a resolved promise we use then() function and the catch() function to create output for the result. In response, we get the string that we print. 


Example:

 In this example, we will use fetch() API to make XMLHttpRequest with the server.



Output

{ userId:1 ,id:1 ,title : "delectus aut autem" ,completed : false

__proto__:Object }

Title of our response :  delectus aut autem

We will get back to you via email or phone call