Page 188 - Computer Software Application TP - Volume 1
P. 188
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 46 : Implementing an AJAX application
Objectives
At the end of this exercise you shall be able to
• handle AJAX request
• update HTML page content dynamically
Requirements
Tools/Materials
• Desktop / Laptop with latest configuration
• Text editor
• Web browser
• Apache web server
Procedure
TASK 1: Implementation an AJAX application
I Create a JavaScript file to handle the AJAX request and update the content dynamically.
1 Open the text editor
2 Write the following codes
// Get references to the button and content container
const loadButton = document.getElementById(‘loadButton’);
const contentContainer = document.getElementById(‘contentContainer’);
// Function to load content asynchronously
function loadContent() {
// Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Define the callback function to handle the response
xhr.onreadystatechange = function() {
// Check if the request is complete and successful
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Update the content container with the response text
contentContainer.innerHTML = xhr.responseText;
}
};
// Open a GET request to the desired URL
xhr.open(‘GET’, ‘example.txt’, true);
// Send the request
xhr.send();
}
// Add an event listener to the button to trigger the AJAX request
loadButton.addEventListener(‘click’, loadContent);
173