Ran HTML through local server so that parse a text file that is written in XML format. Inside the XMLHttpRequest function, I am able to print the node of the xmlDoc variable I want. But then outside the XMLHttpRequest function, it basically forgets what is stored in the xmlDoc variable.
Why, am I not able to bring the parsed XML xmlDoc variable output out of the XMLHttpRequest function?
HTML
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
</body>
<script>
var xmlDoc = new DOMParser();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(this.responseText,"text/xml");
console.log(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue)
}
};
xhttp.open("GET", "project_content.txt", true);
xhttp.send();
console.log(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue)
</script>
</html>
TXT File
<projects>
<mini_title>
COVID-19 POWER BI
</mini_title>
<title>
COVID-19 POWER BI
</title>
<techniques>
SQL, DAX, Micorsoft SQL Sever, and Power BI
</techniques>
<about>
random text
</about>
<mini_title>
FOREX ML TRADER
</mini_title>
<title>
FOREX MACHINE LEARING AUTO TRADER
</title>
<techniques>
Python, Object-Oriented Programming, GUI, MetaTrader 5 Python Package, and Machine Learning
</techniques>
<about>
random text
</about>
</projects>
Expected outcome (chrome console):
COVID-19 POWER BI
COVID-19 POWER BI
Actual outcome (chrome console):
[tester.html:57 Uncaught TypeError: xmlDoc.getElementsByTagName is not a function at tester.html:57
tester.html:51 COVID-19 POWER BI
]1