Loading a Message with AJAX on Button Click

Learn how to load a message using AJAX on button click with a simple XMLHttpRequest example that updates content without page reload.

Brief Introduction

Loading a Message with AJAX on Button Click (ajax)
DESCRIPTION:
Simple and complete example showing how to load a message from a simulated server using AJAX on a button click, without reloading the page.

ADDITIONAL NOTES:
The file 'messaggio.txt' must be present in the same folder as the HTML file and contain the text to display. This example works on local or remote servers, not by directly opening the HTML file from the filesystem due to CORS restrictions.

EXPLANATIONS:
- The button with id 'caricaMessaggio' triggers the JavaScript function on click.
- The function creates an XMLHttpRequest object to make an asynchronous GET request to the file 'messaggio.txt'.
- When the response is ready and has status code 200 (OK), the file content is inserted into the div with id 'contenuto'.
- The code is written simply and commented to facilitate understanding even for beginners.

Example Code: ajax

<!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>
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

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)

Similar Topics

First AJAX request to a text file
Learn how to make a basic AJAX request using XMLHttpRequest to load and display a text file content on an HTML page without reloading it.
Display current time from server with AJAX
Learn how to display the current server time on a web page using AJAX with PHP, updating every second without page reload for seamless user experience.
Change the content of a div using AJAX
Learn how to dynamically change the content of a div using pure JavaScript AJAX without reloading the page. Simple example for beginners.
Load a Welcome Message from a JSON File with AJAX
Learn how to load a welcome message from an external JSON file using pure JavaScript AJAX without libraries, ensuring compatibility with old browsers.
Update a paragraph without reloading the page using AJAX
Learn how to update an HTML paragraph dynamically using AJAX with native JavaScript without reloading the page for a seamless user experience.
Perform a Simple GET Request with AJAX in Pure JavaScript
Learn how to perform a simple AJAX GET request using pure JavaScript without external libraries and display server response on an HTML page.
Load a list of names from a JSON file using AJAX
Complete example to load and display a list of names from a JSON file using AJAX with pure JavaScript and XMLHttpRequest for full browser compatibility.
Show an error message if the AJAX request fails
Learn how to show an error message if an AJAX request fails using XMLHttpRequest with a simple button and output div for clear user feedback.