AJAX (Asynchronous JavaScript and XML)

Fetch API Example:

                                      
                                        <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Async Request Example</title>
</head>
<body>

    <button id="getDataBtn">Get Data</button>
    <div id="result"></div>

    <script>
        document.getElementById('getDataBtn').addEventListener('click', fetchData);

        function fetchData() {
            // Make an asynchronous request using the Fetch API
            fetch('https://jsonplaceholder.typicode.com/todos/1')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // Update the content dynamically
                    document.getElementById('result').innerHTML = `
                        <p>User ID: ${data.userId}</p>
                        <p>Title: ${data.title}</p>
                        <p>Completed: ${data.completed ? 'Yes' : 'No'}</p>
                    `;
                })
                .catch(error => {
                    console.error('Error:', error.message);
                });
        }
    </script>

</body>
</html>
                                                       
                                      
                                    

In this example:


  • The fetch function is another way of making an asynchronous request to fetch data from a URL, in this case the JSONPlaceholder API which provides a sample todo.
  • The then method is utilized to manage the response. In the case of a successful response, they are converted to JSON format or some designated format.
  • The second then block takes the JSON data and parses it for the update of the content of ‘result’ div.
  • The catch block deals with any exception that may occur when running the code segment, and prints the error message to the console.
Note:
  • If you were to put the script in practice, you would most probably need to consider loading states, error messages, and other design-related issues.
  • CORS should be supported by your server if you are making requests to a different domain from the one the application is hosted on.
Hey there! Let's go for Learn fasta then! It is more than just coding; it is to have the superpower that can solve any problem. Through simple and easy-to-grasp examples you will sail through the learning process. In addition, it is not just about coding– you will acquire competencies on how to solve complex problems, analyze data, and come up with efficient solutions. Shall we start this wonderful journey together! learnfasta.com terms of use, Copyright 2025 All Rights Reserved.