The problem is that fetch
performs its tasks asynchronously and you are trying to access Data
before its value is available.
Please try the following code.
I recommend you to read more about JS Promises and asynchronous code execution. However, if you have any doubt, please let me know.
<html>
<head>
<title>Untitled</title>
</head>
<body>
<p id='demo'> </p>
<script type="text/javascript">
let Data = null;
let myFunction = function () {
console.log('DATA IS NOT READY YET.');
};
fetch('fetch.php')
.then(data => data.json())
.then(data => {
myFunction = function () {
document.getElementById('demo').innerHTML = data[1].name;
};
});
</script>
<button onclick="myFunction()">Click me</button>
</body>
</html>
I’m trying to print one of my data strings in HTML paragraph to test if the data is working. However, when I try and getElementById I get the error above. Although when I use a button to call the function I have no issues in printing the data. I think this has something to do with the order the data is read in, but I’m not quite sure. The code I have used is as follows:
<html>
<head>
<title>Untitled</title>
</head>
<body>
<p id="demo"> </p>
<script type="text/javascript">
//Stores data
var Data = null;
fetch('fetch.php')
.then(data => data.json())
.then(data => {
//Set data
Data = data;
console.log(Data);
});
document.getElementById("demo").innerHTML = Data[1].name;
function myFunction() {document.getElementById("demo").innerHTML = Data[1].name;}
</script>
<button onclick="myFunction()">Click me</button>
</body>
</html>
If you have any further questions please ask as I was struggling how to word this. Thanks in advanced!