Mastering AJAX in JavaScript: A Beginner’s Guide with Examples

JavaScript-World
4 min readMay 5, 2023
Photo by Pankaj Patel on Unsplash

Asynchronous JavaScript and XML (AJAX) is a powerful web development technique that enables you to create dynamic, interactive, and responsive web applications. AJAX allows you to fetch data from a server and update parts of a web page without needing to reload the entire page. In this blog post, we will introduce AJAX, explain how it works, and provide practical examples to help you understand and implement AJAX in your JavaScript projects.

1. What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It is a set of web development techniques that use various web technologies on the client-side to create asynchronous web applications. With AJAX, you can send and receive data from a server without interfering with the display and behavior of the existing page. AJAX is not a single technology, but a combination of several technologies, including HTML, CSS, JavaScript, and the XMLHttpRequest object.

2. The XMLHttpRequest Object

The XMLHttpRequest object is the core component of AJAX, as it provides a way to communicate with the server and exchange data asynchronously. XMLHttpRequest is a JavaScript object that allows you to perform HTTP requests and handle the responses directly in JavaScript.

3. Performing a Simple GET Request

To perform an AJAX request using the XMLHttpRequest object, you can follow these steps:

  • Create a new XMLHttpRequest object
  • Set up a callback function to handle the response
  • Open the request, specifying the HTTP method and the URL
  • Send the request

Here’s a basic example of performing a GET request using AJAX:

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.send();

In this example, we fetch a list of posts from the JSONPlaceholder API, an online REST API for testing and prototyping. The onreadystatechange event handler checks if the request is completed (readyState === 4) and successful (status === 200), and then logs the response text to the console.

4. Handling JSON Data

In many cases, you’ll be working with JSON data when using AJAX. Here’s an example of how to fetch JSON data and parse it using AJAX:

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const jsonData = JSON.parse(xhr.responseText);
console.log(jsonData);
}
};
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.send();

In this example, we use the JSON.parse() method to convert the response text into a JavaScript object, which we can then work with more easily.

5. Performing a POST Request

To perform a POST request using AJAX, you can follow the same steps as for a GET request, but specify the “POST” method and send the data as a JSON string:

const xhr = new XMLHttpRequest();
const data = JSON.stringify({ title: "New Post", body: "This is a new post.", userId: 1 });
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 201) {
console.log(xhr.responseText);
}
};
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);

In this example, we create a new post and send it to the JSONPlaceholder API. We use the JSON.stringify() method to convert the JavaScript object into a JSON string, and set the "Content-Type” header to “application/json;charset=UTF-8” to inform the server that we’re sending JSON data. The onreadystatechange event handler checks for a successful request (status === 201), indicating that the new post has been created.

6. Error Handling

When working with AJAX, it’s important to handle errors that may occur during the request. You can use the onerror event handler to handle network errors and check the status property in the onreadystatechange event handler to handle HTTP errors:

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const jsonData = JSON.parse(xhr.responseText);
console.log(jsonData);
} else {
console.error("Error: " + xhr.status);
}
}
};
xhr.onerror = function() {
console.error("Network Error");
};
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.send();

In this example, we’ve added an onerror event handler to handle network errors, and we check the status property in the onreadystatechange event handler to handle HTTP errors.

7. Real-World Example: Fetching and Displaying Posts

Let’s create a simple web application that fetches and displays a list of posts using AJAX.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fetching Posts</title>
</head>
<body>
<h1>Posts</h1>
<ul id="posts"></ul>
  <script src="posts.js"></script>
</body>
</html>

JavaScript (posts.js):

const xhr = new XMLHttpRequest();
const postsElement = document.getElementById("posts");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const posts = JSON.parse(xhr.responseText);
displayPosts(posts);
}
};
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
xhr.send();
function displayPosts(posts) {
posts.forEach(post => {
const postItem = document.createElement("li");
postItem.innerText = `${post.title} - ${post.body}`;
postsElement.appendChild(postItem);
});
}

In this example, we fetch a list of posts from the JSONPlaceholder API and display them as list items in an unordered list. The displayPosts() function iterates through the posts array, creates an li element for each post, sets its text content to the post title and body, and appends it to the posts element.

Conclusion

In this blog post, we’ve introduced AJAX and explained how to use the XMLHttpRequest object to perform asynchronous requests in JavaScript. We’ve covered performing GET and POST requests, handling JSON data, error handling, and showcased a real-world example of fetching and displaying posts.

By understanding and implementing AJAX in your web applications, you can create more dynamic, interactive, and responsive experiences for your users. As you continue to explore AJAX and other web technologies, you’ll be able to build increasingly sophisticated and engaging web applications.

If you enjoyed the article and would like to show your support, be sure to:

👏 Applaud for the story (50 claps) to help this article get featured

👉Follow me on Medium

Check out more content on my Medium profile

--

--

JavaScript-World

Elevating web experiences with 10+ yrs in JS🚀.Crafting seamless UIs,optimizing performance, mentoring next-gen coders.Passionate about learning&innovation.🌐✨