How to create own Ajax functionality?


An Ajax (Asynchronous JavaScript and XML) request is an HTTP request made using JavaScript, typically with the XMLHttpRequest object, to exchange data with a server and update a specific part of a web page without requiring full page refresh. There are two ways to create own Ajax functionality. You can use JSONPlaceholder API or your own file. We will discuss these two ways in detail in this tutorial.

Using JSONPlaceholder API

JSONPlaceholder is a free online REST API that you can use to test and practice your development skills

Syntax

Users can follow the below syntax for creating an Ajax request using JavaScript's “XMLHttpRequest” object.

let xhr = new XMLHttpRequest();
xhr.open("HTTP_METHOD" , "API_URL" , true); 

//HTTP_METHOD can be "GET" , "POST" , "PUT", etc.
xhr.onload = function(){
   if(xhr.status === 200) {
      
      //handle the response
   } else {
      
      //show xhr.status
   }
};
xhr.send();

This will create a new XMLHttpRequest object, open a connection to the specified API_URL using the specified HTTP_METHOD, and send the request. The onload function will be called when the request is complete, and the xhr.status property will contain the HTTP status code of the response. You can handle the response data in the onload function and update your HTML, JavaScript or JSON accordingly.

Please remember that you will need to provide your API_URL and check the API documentation to know the right HTTP_METHOD and parameters to use.

Steps

Follow the below steps to create own Ajax functionality using JSONPlaceholder API −

Step 1 − Create a button element on the HTML page with an onclick event that calls the getUsers() function.

Step 2 − Create an unordered list element with an id attribute of "user-list" and a div element with an id attribute of "error" on the HTML page.

Step 3.1 − Create a new XMLHttpRequest object and assign it to a variable named "xhr".

Step 3.2 − Open a new GET request to the specified API URL using the xhr object and set the request to be asynchronous.

Step 4.1 − Set the “onload” function of the xhr object to be called when the request is completed.

Step 4.2 − In the “onload” function, check the “xhr.status” property of the xhr object.

Step 4.3 − If the status code is 200 −

  • Parse the responseText of the xhr object and assign the resulting object to a variable "users".

  • Assign the element with the id "user-list" to a variable "list".

  • Create a for loop that iterates for the length of the "users" object.

  • In the for loop, create a new list item element, set its innerHTML to the name property of the current user, and append it to the "list" element.

Step 4.4 − If the status code is not 200, update the error div with the status code.

Step 5 − Send the request to the server.

Example

Here is an example of how you could create your own Ajax functionality using JavaScript and the JSONPlaceholder API, which is a free, open-source API for testing and prototyping.

This example shows a simple HTML page that retrieves a list of users from the API and displays their names in a list.

<html>
<body>
   <h3>User List</h3>
   <button onclick = "getUsers()"> Get Users </button> 
   <ul id = "user-list"></ul>
   <div id = "error" > </div>
   <script>
      function getUsers() {
         let xhr = new XMLHttpRequest();
         xhr.open("GET", "https://jsonplaceholder.typicode.com/users", true);
         xhr.onload = function() {
            if (xhr.status === 200) {
               let users = JSON.parse(xhr.responseText);
               let list = document.getElementById("user-list");
               list.innerHTML = "";
               for (let i = 0; i < users.length; i++) {
                  let li = document.createElement("li");
                  li.innerHTML = users[i].name;
                  list.appendChild(li);
               }
            } else {
               let error = document.getElementById("error");
               error.innerHTML = "Error: " + xhr.status;
            }
         };
         xhr.send();
      }
   </script>
</body>
</html>

Using Our Own File

We can also create Ajax requests using our own file. We need to give a file path instead of API_URL.

Syntax

Follow the below syntax for creating an Ajax request using this method.

let xhr = new XMLHttpRequest();
xhr.open("HTTP_METHOD" , "FILE_PATH" , true);

FILE PATH is the URL of the file or resource you want to request. This could be a web page, an image, a JSON file, a text file etc. "true" means that the request is asynchronous, and the script will continue to execute while the request is being processed.

Steps

Follow the below steps to create own Ajax functionality using our own file −

Step 1 − Create an instance of the XMLHttpRequest object.

Step 2 − Open a GET request to "example.txt" (If the file is located in a sub-directory, you can specify the directory and file name).

Step 3 − Add an onload event listener; in the onload event, check the request status.

Step 3.1 − If the status is 200, read the file's content and set it to variable 'fileContent'. Get the element with id 'file-content' and set the innerHTML of the element to the fileContent.

Step 3.2 − If the status is not 200, get the element with id 'error' and set the innerHTML of the element to an error message with the status code.

Step 4 − Send a request to the server.

Example

An “example.txt” is a text file with the message: “You are reading an example text file.” You can replace "example.txt" with the actual name of your text file and make sure that the text file is in the same directory as the HTML file or give your file name with the directory.

Here is an example of how you can use an Ajax request to read a text file and display its contents on a webpage.

<html>
<body>
   <h3>Text File Reader</h3>
   <button onclick = "readTextFile()"> Read Text File </button>
   <div id = "file-content" ></div>
   <div id = "error" > </div>
   <script>
      function readTextFile() {
         let xhr = new XMLHttpRequest();
         xhr.open("GET" , "/about/topics_list.txt" , true);
         xhr.onload = function() {
            if (xhr.status === 200) {
               let fileContent = xhr.responseText;
               let contentDiv = document.getElementById("filecontent");
               contentDiv.innerHTML = fileContent;
            }
            else {
               let error = document.getElementById("error"); 
               error.innerHTML = "Error: " + xhr.status;
            }
         };
         xhr.send();
      }
   </script>
</body>
</html>

Note that the status code 200 is the standard response for a successful HTTP request. It indicates that the server received, understood, and accepted the request.

Please note that this code will only work if your text file is on the same domain as your HTML file; if you try accessing a file from another domain, you will get a CORS error.

We have learned to use JSONPlaceholder API to create an Ajax request using JavaScript's XMLHttpRequest object and to use our own file for creating an Ajax request.

Updated on: 28-Feb-2023

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements