Learn how to load a message using AJAX on button click with a simple XMLHttpRequest example that updates content without page reload.
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<title>Loading message with AJAX</title>
</head>
<body>
<!-- Button to load the message -->
<button id="caricaMessaggio">Load message</button>
<!-- Div where the loaded message will be displayed -->
<div id="contenuto" style="margin-top:20px; font-weight:bold;"></div>
<script>
// Select the button by its id
var bottone = document.getElementById('caricaMessaggio');
// Add a click listener to the button
bottone.addEventListener('click', function() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure the request: GET method, URL of the file to load, asynchronous
xhr.open('GET', 'messaggio.txt', true);
// Define what to do when the request state changes
xhr.onreadystatechange = function() {
// Check that the request is complete (readyState 4)
// and that the response is OK (status 200)
if (xhr.readyState === 4 && xhr.status === 200) {
// Insert the received text into the div with id 'contenuto'
document.getElementById('contenuto').textContent = xhr.responseText;
}
};
// Send the request
xhr.send();
});
</script>
</body>
</html>HTML: button with id 'caricaMessaggio' and div with id 'contenuto' to display the message
JavaScript: AJAX code with XMLHttpRequest to load data from a simulated endpoint
DEPENDENCIES: no external libraries, only native JavaScript
CONFIG: simulated endpoint with URL 'messaggio.txt' (text file containing the message to load)