Skip to content

Instantly share code, notes, and snippets.

@glennhefley
Created August 21, 2024 18:24
Show Gist options
  • Save glennhefley/7b9074bd60be290a9c59d0d414b43680 to your computer and use it in GitHub Desktop.
Save glennhefley/7b9074bd60be290a9c59d0d414b43680 to your computer and use it in GitHub Desktop.
using Ajax, loads content from a text file into a paragraph tag
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Load Text File with AJAX</title>
</head>
<body>
<h1>Load Content into a Paragraph</h1>
<p id="text-content">This content will be replaced by the text file content.</p>
<button onclick="loadTextFile()">Load Text File</button>
<script>
function loadTextFile() {
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure it: GET-request for the URL of the text file
xhr.open('GET', 'example.txt', true);
// Set up a function to handle the response
xhr.onload = function() {
if (xhr.status == 200) {
// Success! Update the content of the <p> tag
document.getElementById('text-content').innerText = xhr.responseText;
} else {
// If there was a problem, alert the user
alert('Failed to load the file.');
}
};
// Send the request
xhr.send();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment