0

I am developing a trivia page with a series of questions that I get through an API. When I give to start the game on the main page, I want to redirect me to a second page where the available categories will appear and when I click on them, the questions will appear with multiple answers.

Luckily I have managed to do all this, however, when I switch from one page to another I have not been able to get the categories to appear. They only appear if I am already on that page and I create a button to call the function that displays them.

I had thought of doing this function in this way so that it would switch me to the other page and then load the questions but I have not been able to get it to work.

Does anyone have a solution or know why it is not working?

function get_dataJson() {
    let data_json = [];
    fetch('https://opentdb.com/api.php?amount=10')
    .then(response => response.json())
    .then(data => data.results.forEach(element => {
        data_json.push(element);
    }));
    return data_json;
}

let trivial_data = get_dataJson();

function startGame() {
    let div_username = document.createElement("div");
    let name = document.createElement("h2");
    name.innerHTML = document.getElementById("name").value;
    div_username.appendChild(name);
    let categories = get_categories(trivial_data);
    
    setTimeout("location.href='./game.html'", 1000);
    
    setTimeout(function(){
        document.getElementById('nav-game').appendChild(div_username);
        show_categories(categories);
    },2000);
}

function get_categories(trivial_data) {
    let categories = [];
    trivial_data.forEach(element => {
        categories.push(element.category)
    });
    console.log(categories);
    return categories;
}

function show_categories (categories) {
    let div_categories = document.createElement("div");
    let count = 0;
    categories.forEach ( element => {
        let element_category = document.createElement("button");
        element_category.innerHTML = element;
        element_category.id = count;
        element_category.onclick = function() {
            get_question(element_category.id);
        };
        count++;
        div_categories.appendChild(element_category);
    });
    div_categories.className = 'categories';
    document.getElementById("categories").appendChild(div_categories);
}


function get_question (pos) {
    document.getElementById("categories").style.displays = 'none';
    let question = document.createElement("h2");
    question.innerHTML = trivial_data[pos].question;

    let correct_answer = trivial_data[pos].correct_answer;
    let incorrect_answers = trivial_data[pos].incorrect_answers;
    let options = incorrect_answers.concat(correct_answer);
    options = options.sort();
    
    let div_choices = document.createElement("div");
    options.forEach(element => {
        let choice = document.createElement('button');
        choice.innerHTML = element;
        choice.id = 'true' ? element == correct_answer : 'false';
        div_choices.appendChild(choice);
    });

    div_choices.className = 'answers';
    document.getElementById("questions").appendChild(question);
    document.getElementById("questions").appendChild(div_choices);
    
}
  • There's a lot of code here. Which part specifically is not working? What is it doing instead? and what should it do? – evolutionxbox May 19 '21 at 11:51
  • Does this answer your question? [Why is setTimeout(fn, 0) sometimes useful?](https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful) – Rahul Kumar May 19 '21 at 11:52
  • 3
    Your title does not seem to match the body of your question. It's not clear what part you're having problems with but I can tell you your `get_dataJson` method will not be doing what you think it is doing. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Jamiec May 19 '21 at 11:52
  • The part that doesn't work is the StartGame(), my idea of the function is to redirect to second page, put in the – Joaking May 19 '21 at 11:54
  • But once you redirect to a different page the javascript on the current page will not run. Why are you changing page at all? – Jamiec May 19 '21 at 11:55
  • I was changing pages, because I thought it would be the best way, but I think thanks to your answer I know why it doesn't work for me. Instead of using two pages, I can hide the start button and show the categories on the same page so that it uses the same scripts.js. That's the reason for the error, isn't it? Because it is not loading again the scripts.js (I do not know if I am explaining myself well). – Joaking May 19 '21 at 11:59

1 Answers1

1

The first thing you should do is make sure you understand how to use fetch to get data asynchronously

async function get_dataJson() {
    
    const response = await fetch('https://opentdb.com/api.php?amount=10');
    const json = await response.json();
    return json.results;
}

(async function(){
  const trivial_data = await get_dataJson();
  console.log(trivial_data);
})()

Then, rather than changing page, just stay on the same page and add/remove/hide elements as necessary - it looks like you have that bit sorted.

Jamiec
  • 133,658
  • 13
  • 134
  • 193