DeveloperBreeze

Javascript Ajax Development Tutorials, Guides & Insights

Unlock 1+ expert-curated javascript ajax tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your javascript ajax skills on DeveloperBreeze.

AJAX with JavaScript: A Practical Guide

Tutorial September 18, 2024
javascript

Before the Fetch API, the traditional way to make AJAX requests was using XMLHttpRequest.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX with XMLHttpRequest</title>
</head>
<body>
    <button id="fetchDataBtn">Fetch Data</button>
    <div id="dataOutput"></div>

    <script>
        document.getElementById('fetchDataBtn').addEventListener('click', function() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

            xhr.onload = function() {
                if (this.status === 200) {
                    var data = JSON.parse(this.responseText);
                    document.getElementById('dataOutput').innerHTML = `
                        <h3>${data.title}</h3>
                        <p>${data.body}</p>
                    `;
                }
            };

            xhr.onerror = function() {
                console.error('Request failed.');
            };

            xhr.send();
        });
    </script>
</body>
</html>