this is my second question today but I feel I'm so close to get this right that I just had to do it...
Long story short: I'm developing a flashcard web app using JSON files as a database. My previous question: Loop through JSON object properties and show one at a time in a text button every time is clicked - flashcard concept.
I managed to get the response from the JSON file using a function (getSSIIData). However, when I try to store the result in a variable (jsonSSII) so that I can manipulate it afterwards, I get this error:
"VM454:1 Uncaught SyntaxError: "undefined" is not valid JSON
at JSON.parse (<anonymous>)
at app.js:28:24"
Which is confusing, because when I try this with an array of objects stored in a variable in the same Javascript file it DOES work. E.g:
var jsonSSII = `[
{
"subject": "Database",
"concept": "Relational data model",
"definition": "An abstract model used to organize and manage the data..."
},
{
"subject": "Database",
"concept": "Information system",
"definition": "An integrated set of components for collecting, storing..."
}
]`;
However, it does not work with the text response I get from the JSON file, although it looks exactly the same when I console.log it.
This is what I have so far:
var clicks = -1;
var button = document.querySelector("#ssii-button");
var jsonSSII = (function getSSIIData() {
const requestData = new XMLHttpRequest();
requestData.open("GET", "data-ssii.json", true);
requestData.send();
requestData.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = this.responseText;
console.log(this.responseText);
return data;
}
};
})();
var contentSSII = JSON.parse(jsonSSII);
const buttonText = contentSSII.reduce((acc, cur) => {
for (let key in cur) {
if (key != "subject") {
acc.push(cur[key]);
}
}
return acc;
}, []);
function showContent() {
clicks += 1;
button.innerHTML = buttonText[clicks];
}
button.addEventListener("click", showContent);
Thanks a million times for your help!