Harshil Chovatiya - Day 22: AJAX and Fetch API

Harshil Chovatiya - Day 22: AJAX and Fetch API

Harshil Chovatiya - Day 22: AJAX and Fetch API

Harshil Chovatiya - Day 22: AJAX and Fetch API

Today, we'll explore Asynchronous JavaScript and XML (AJAX) and the Fetch API. These technologies allow you to make asynchronous HTTP requests and retrieve data from web servers without reloading the entire web page.

Understanding AJAX:

AJAX is a set of web development techniques that allow you to send and receive data from a web server without having to reload the entire web page. It stands for Asynchronous JavaScript and XML, although nowadays, JSON is often used instead of XML for data interchange.

Making an AJAX Request:

To make an AJAX request in JavaScript, you typically use the XMLHttpRequest object or the more modern Fetch API. In this lesson, we'll focus on the Fetch API because it provides a more straightforward and promise-based approach.

Example using Fetch API:

                
                
    // Define the URL of the API you want to fetch data from
    const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';
    
    // Make a GET request using the Fetch API
    fetch(apiUrl)
      .then(response => {
        // Check if the response status is OK (status code 200)
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        // Parse the JSON data from the response
        return response.json();
      })
      .then(data => {
        // Handle the data
        console.log(data);
      })
      .catch(error => {
        // Handle any errors
        console.error('Fetch error:', error);
      });
                
            

Sending Data with POST Request:

                
                
    const apiUrl = 'https://jsonplaceholder.typicode.com/posts';
    
    const postData = {
      title: 'My New Post',
      body: 'This is the content of my post.',
      userId: 1,
    };
    
    fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(postData),
    })
      .then(response => response.json())
      .then(data => {
        console.log('Posted data:', data);
      })
      .catch(error => {
        console.error('Fetch error:', error);
      });
                
            

Conclusion:

AJAX and the Fetch API are essential tools for building modern web applications. They allow you to fetch data from servers and update your web page dynamically, providing a smoother and more responsive user experience. As you continue to explore web development, mastering AJAX and Fetch will be invaluable for building interactive and data-driven websites.

Social Media

Comments