Hello everyone, I’m practicing AJAX. The idea of this project is to click on 1 of 2 buttons that will show some different text, the output text depends on which button is clicked. My first part below is my original work and it satisfied my need.
<p id="output1"></p>
<p id="output2"></p>
<div id="click">
<button id="button1">button 1</button>
<button id="button2">button 2</button>
</div>
<script src="app.js"></script>
FIRST PART:
const p1 = document.getElementById("output1");
const button1 = document.getElementById("button1");
button1.addEventListener("click", loadText);
function loadText() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "text.txt", true);
xhr.onload = () => {
if (xhr.status == 200) {
p2.textContent = "";
p1.textContent = xhr.responseText;
}
}
xhr.send();
}
const p2 = document.getElementById("output2");
const button2 = document.getElementById("button2");
button2.addEventListener("click", loadText2);
function loadText2() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "text2.txt", true);
xhr.onload = () => {
if (xhr.status == 200) {
p1.textContent = "";
p2.textContent = xhr.responseText;
}
}
xhr.send();
}
Then I tried to make it more compact(imagine how hard it will be if I have 5 or 10 buttons do the same function).
So here is my solution:
SECOND PART:
const buttons = document.getElementById("click");
buttons.addEventListener("click", click);
function click (event) {
//dynamically select a button by event delegation
const target = event.target;
const xhr = new XMLHttpRequest();
//check which exactly button is clicked
if (target.id == "button1") {
xhr.open("GET", "text.txt", true);
} else if (target.id == "button2") {
xhr.open("GET", "text2.txt", true);
}
//show text
xhr.onload = () => {
const p1 = document.getElementById("output1");
const p2 = document.getElementById("output2");
if (xhr.status == 200) {
p1.textContent = xhr.responseText;
}
}
xhr.send();
}
it works! But I don’t understand why it works. Without setting p1/p2.textContent = “”.
The line of code “p1.textContent = xhr.responseText” was “target.textContent = xhr.responseText” but then I realized that I was printing text inside button’s field so that one came up.
p/s: it works if there are 2 buttons only.