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.