Testing async before making more complex code. I have an HTML file that tries to get a dataset using an async fetch function, located in a Javascript file, from my database. I want to store the dataset in a variable inside the HTML file which would then place it inside a SPAN HTML element tag. When executing and looking at my browser log, I can see that the dataset has been retrieved from the database, but it is not returning to be stored in the HMTL var. I have tried some solutions, but they have not worked. I would appreciate knowing why they did not work and a solution, please.
CODES: HTML FILE:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="queryFile.js"></script>
</head>
<body>
<h2>The XMLHttpRequest Object</h2>
<h3>Start typing a name in the input field below:</h3>
<p>Suggestions: <span id="txtHint"></span></p>
<p>First name: <input type="text" id="txt1" ></p>
</body>
<script>
const seeing = getBuyData("fff","2ddds");
console.log(seeing)
document.getElementById("txtHint").innerHTML = seeing;
</script>
CODES: JAVASCRIPT FILE:
async function getBuyData(starter, ender) {
if (starter.length == 0) {
console.log("No Data to POST");
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var gotten_Text = this.responseText;
console.log(gotten_Text) //THIS PART WORKED
return gotten_Text;
}
xmlhttp.open("POST", "getFXData.php?case01=1&str=" + starter + "&ed=" + ender);
xmlhttp.send();
}
}
THE FOLLOWING BELLOW ARE MY ATTEMPTED SOLUTIONS:
1)
document.getElementById("txtHint").innerHTML = getTheData("fff","2ddds");
const seeing = getBuyData("fff","2ddds");
console.log(seeing)
document.getElementById("txtHint").innerHTML = seeing;
getBuyData("fff","2ddds").then(
function(value) {
document.getElementById("txtHint").innerHTML = value;;
},
function(error) {
console.log(error);
}
);
async function getTheData01() {
var fstep = await getBuyData("fff","2ddds");
document.getElementById("txtHint01").innerHTML = fstep;
}