Having an issue where data from a JSON file is loading after a function has completed in JavaScript, causing it to not display properly in the browser. I've been researching alternative solutions through this stackoverflow post which offers some workarounds, but my challenge lies in implementing these without relying on JQuery. While JQuery would simplify the process, I'm restricted to using pure JavaScript only.
To retrieve the JSON information:
// Function to fetch JSON data
this.getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
}
Next, the JSON data is transformed into a JavaScript object:
this.GetQuiz = function () {
var thisQuiz = this;
// Retrieve quiz information from the JSON folder
app.getJSON('json/demo.json', function(err, data) {
if (err != null) { // Handle errors
console.log('Unable to load quiz: ' + err);
} else {
// Assign data to object properties
this.Title = data.title;
this.Introduction = data.longtitle;
this.HeroImage = imgBase + 'products/' + data.img;
this.About = data.extra;
// Set How To Play text based on quiz type
if(this.Type == 'Knowledge') {
this.HowToPlayText = "Knowledge, how to play text...";
} else if (this.Type == 'Identity') {
this.HowToPlayText = "Identity, how to play text...";
} else if (this.Type == 'TrueFalse') {
this.HowToPlayText = "True/false, how to play text...";
}
console.log('Loading quiz for ' + this.Title + ' range');
thisQuiz.GetQuestions(); // Load Questions
}
}.bind(this));
}.bind(this);
A separate function is called to display parts of the object in the browser:
this.QuizSelection = function () {
// Update elements with quiz info
app.SetBackground('head', this.HeroImage);
console.log('1 ' + this.HeroImage);
app.LoadInnerHTML('breadcrumbs', 'Home / ' + this.Title);
app.LoadInnerHTML('quizSelectionTitle',this.Title);
console.log('2 ' + this.Title);
app.LoadInnerHTML('quizSelectionIntro',this.Introduction);
console.log('3 ' + this.Introduction);
app.ShowSection('head'); // Show Quiz Selection and Heading
app.ShowSection('quizSelection');
console.log('Quiz Selection');
}.bind(this);
Both functions are triggered upon page load:
window.onload = function () {
var quiz = new QuizBase('Knowledge', 'Product');
quiz.GetQuiz();
quiz.QuizSelection();
}
The main goal is to execute quiz.QuizSelection();
only after quiz.GetQuiz();
has finished processing.