I'm making a simple HTML webpage with some JavaScript. I take information from a JSON file, and with help of JavaScript, I format the text and prepare it to export to a CSV file.
The problem comes when I write the text on the page, and after I try to read it. It gives me an Empty string, so I can't export it.
For testing, I'm just writing the output with console.log
, but I'm not getting the response that I expect.
JavaScript
document.addEventListener('DOMContentLoaded', function () {
convertData();
});
function convertData() {
fetch('info.json')
.then(response => response.json())
.then(data => showData(data))
.then(print())
.catch(error => console.error('Error:', error));
}
function showData(data) {
const container = document.getElementById("container");
for (var i = 0; i < data["data"].length; i++) {
var obj = data["data"][i];
container.innerHTML += "<br>" + obj["field1"] + "; " + obj["field2"] + "; "
}
}
function print() {
const container = document.getElementById("container");
const data = container.innerHTML;
console.log(data);
}
HTML
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
</body>
</html>
When I use container.innerHTML += "....."
, it shows me the content correctly, but when I print it, it doesn't show properly.
I can't use TimeOuts
, because I don't know how long it can take. It can be 3 seconds on the first time and 40 seconds con the second one.