Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

Introduction to AJAX (Asynchronous JavaScript and XML)

Welcome to Module 7! In this journey, you will become a master of AJAX, a powerful technique that allows your web pages to communicate with servers asynchronously, without the need to reload the entire page.

Imagine you are in a restaurant and place an order with the waiter. While waiting for your dish, you don’t just stand still doing nothing, right?

You can use that time to chat with friends, read a book, or even continue enjoying the appetizers that have been served.

This is the idea behind AJAX, which stands for Asynchronous JavaScript and XML.

It is a way to make requests to the server and get responses without blocking the execution of the rest of the code.

Just like you don’t stand still waiting for your dish, AJAX allows you to perform other tasks while waiting for the server’s response.

But why XML in the name? Although AJAX was popularized using XML to transport data between the client and the server, it is more common nowadays to use the JSON (JavaScript Object Notation) format, which is lighter and easier to manipulate.

Imagine you are on a news website and want to view new articles.

Instead of refreshing the entire page, AJAX allows you to make a request to the server to fetch only the new articles and dynamically update this information on the page without interrupting your current reading.

AJAX is widely used in web applications to improve the user experience, making pages faster and more interactive.

It is especially useful in situations where it is necessary to fetch information from the server asynchronously, such as in search forms, dynamic content updates, and interaction with external APIs.

To implement AJAX in JavaScript, we use the Fetch API, which is a more modern and straightforward way to make asynchronous requests. With it, we can send and receive data from the server efficiently.

In summary, AJAX is like an efficient waiter that allows you to do other activities while waiting for the server’s response.

It makes web applications more dynamic, enabling content updates without the need to reload the entire page.

I hope this explanation has been clear, and you have grasped the basic concept of AJAX.

It is a fundamental topic for web development, and with practice, you will be able to make the most of AJAX’s potential in your projects.

Let’s create an example to enhance understanding:

This JavaScript code performs an asynchronous HTTP request using the XMLHttpRequest object to obtain data from an API. Let’s explain each part:

Creation of the XMLHttpRequest object:

   var xhr = new XMLHttpRequest();

Here, an instance of the XMLHttpRequest object is created, allowing HTTP requests.

Configuration of the request:

xhr.open("GET", "https://api.example.com/products");

The open method configures the request, indicating the type (GET, in this case) and the URL of the API to be called.

Definition of the expected data type:

 xhr.responseType = "json";

This indicates that the expected response from the API is in JSON format.

Sending the request:

xhr.send();

The send method sends the request to the server.

Handling the response:

   xhr.onload = function() {
     if (xhr.status === 200) {
       // Success!
       var products = xhr.response;
       // Update the web page with the products
       // ...
     } else {
       // Error!
       console.error("Error loading products:", xhr.statusText);
     }
   };

The onload event is triggered when the request is completed. If the status is 200 (OK), the response data (in JSON format) is accessed through the variable products and can be used to update the page. Otherwise, an error is logged to the console.

Complete code:

// Create a request to the server
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/products");

// Define the expected data type
xhr.responseType = "json";

// Send the request
xhr.send();

// Listen for the response event
xhr.onload = function() {
  if (xhr.status === 200) {
    // Success!
    var products = xhr.response;
    // Update the web page with the products
    // ...
  } else {
    // Error!
    console.error("Error loading products:", xhr.statusText);
  }
};

This code is a basic implementation of an AJAX request to obtain data from an API and handle the response.

Challenge:

Create a web page that uses AJAX to fetch data from an external API (e.g., ZIP code API, weather API).
Display the data on the web page dynamically, without reloading the page.

Now that you understand the concept of AJAX and how it enables asynchronous communication between the client and the server, let’s move on to a related topic: handling JSON data.

During the exploration of AJAX, I mentioned that the JSON format is widely used to transport data efficiently between the client and the server.

Now, let’s learn how to work with JSON data in JavaScript and manipulate it in our projects.

Entrar na conversa
Rolar para cima