Can someone help me with an issue I'm experiencing with code that involves using ajax response outside of a function? Every time I try, it keeps showing undefined. I understand it might be a simple fix, but I'm unsure how to tackle it.
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>test</title>
<script>
var sourceData;
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
sourceData = this.responseText;
//
}
};
xhttp.open("GET", "http://localhost:34560/test/js/source.json", true);
xhttp.send();
document.getElementById("test").innerHTML=sourceData;
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
Update:
Is there a way to use ajax outside the function in this script tag? I would prefer not to have it inside the function.