Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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: using JSONPlaceholder API or your own file.
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 creates a new XMLHttpRequest object, opens a connection to the specified API_URL using the specified HTTP_METHOD, and sends the request. The onload function is called when the request completes, and xhr.status contains the HTTP status code.
Complete Example
This example retrieves a list of users from the JSONPlaceholder 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 Your Own File
You can also create Ajax requests to fetch data from your own files by providing a file path instead of an API URL.
Syntax
let xhr = new XMLHttpRequest();
xhr.open("HTTP_METHOD", "FILE_PATH", true);
FILE_PATH is the URL of the file you want to request (text file, JSON file, etc.). The "true" parameter makes the request asynchronous.
Example: Reading a Text File
This example reads a text file and displays its contents on the webpage. Note the corrected element ID reference.
<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("file-content");
contentDiv.innerHTML = fileContent;
} else {
let error = document.getElementById("error");
error.innerHTML = "Error: " + xhr.status;
}
};
xhr.send();
}
</script>
</body>
</html>
Key Points
Status code 200 indicates a successful HTTP request
Files must be on the same domain to avoid CORS errors
Always handle both success and error cases
Use JSON.parse() for JSON responses
Conclusion
Creating custom Ajax functionality with XMLHttpRequest allows you to fetch data from APIs or local files without page refresh. Always handle both success and error responses for robust applications.
