How to make ajax call from JavaScript ? - GeeksforGeeks

07 Jan, 2022
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 call in JavaScript.
Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server.  
Syntax: 
var xhttp = new XMLHttpRequest();
Above syntax is used to create XMLHttpRequest object. This object has many different methods which are 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: 
Javascript
<script>    function run() {          // Creating Our XMLHttpRequest object         var xhr = new XMLHttpRequest();          // Making our connection          var url = 'https://jsonplaceholder.typicode.com/todos/1';        xhr.open("GET", url, true);          // function execute after request is successful         xhr.onreadystatechange = function () {            if (this.readyState == 4 && this.status == 200) {                console.log(this.responseText);            }        }        // Sending our request         xhr.send();    }    run();</script>
Output: 
"{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}"
Approach 2: 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, function to call when we get our response or if error, etc.
Example: 
HTML
<!DOCTYPE HTML><html>  <head>    <script src="https://code.jquery.com/jquery-3.6.0.min.js">    </script></head>  <body>      <script>          function ajaxCall() {            $.ajax({                  // Our sample url to make request                 url:     'https://jsonplaceholder.typicode.com/todos/1',                  // Type of Request                type: "GET",                  // Function to call when to                // request is ok                 success: function (data) {                    var x = JSON.stringify(data);                    console.log(x);                },                  // Error handling                 error: function (error) {                    console.log(`Error ${error}`);                }            });        }        ajaxCall();    </script></body>  </html>
Output: 
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
Approach 3: 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 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 catch() function to create output for the result. In response, we get the string that we print. 
Example: 
Javascript
<script>      // Url for the request     var url = 'https://jsonplaceholder.typicode.com/todos/1';      // Making our request     fetch(url, { method: 'GET' })        .then(Result => Result.json())        .then(string => {              // Printing our response             console.log(string);                          // Printing our field of our response            console.log(`Title of our response :  ${string.title}`);        })        .catch(errorMsg => { console.log(errorMsg); });</script>
Output: 
{ userId:1 ,id:1 ,title : "delectus aut autem" ,completed : false
__proto__:Object }
Title of our response :  delectus aut autem
rajeev0719singh
JavaScript-Methods
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?