0

I'm new to jQuery and Json and I'm trying to make a quiz.

My problem right now is to retrieve incorrect_answers and correct_answer from Json url file and have them display as answer options for the questions. I'm stuck right now and I'm helpful for all the tips and answers.

 **Json** 

{
  "response_code": 0,
  "results": [
    {
      "category": "History",
      "type": "multiple",
      "difficulty": "medium",
      "question": "What disease crippled President Franklin D. Roosevelt and led him to help the nation find a cure? ",
      "correct_answer": "Polio",
      "incorrect_answers": [
        "Cancer",
        "Meningitis",
        "HIV"
      ]
    },
    {
      "category": "Science: Computers",
      "type": "multiple",
      "difficulty": "easy",
      "question": "What does the Prt Sc button do?",
      "correct_answer": "Captures what's on the screen and copies it to your clipboard",
      "incorrect_answers": [
        "Nothing",
        "Saves a .png file of what's on the screen in your screenshots folder in photos",
        "Closes all windows"
      ]
    },
    {
      "category": "Entertainment: Video Games",
      "type": "multiple",
      "difficulty": "medium",
      "question": "Which puzzle game was designed by a Russian programmer, featuring Russian buildings and music?",
      "correct_answer": "Tetris",
      "incorrect_answers": [
        "Jenga",
        "Boulder Dash",
        "Puzzled"
      ]
    },
    {
      "category": "Geography",
      "type": "multiple",
      "difficulty": "hard",
      "question": "Where is the fast food chain "Panda Express"    headquartered?",
      "correct_answer": "Rosemead, California",
      "incorrect_answers": [
        "Sacremento, California",
        "Fresno, California",
        "San Diego, California"
      ]
    },
    {
      "category": "Entertainment: Video Games",
      "type": "multiple",
      "difficulty": "easy",
      "question": "In what year was Hearthstone released?",
      "correct_answer": "2014",
      "incorrect_answers": [
        "2011",
        "2013",
        "2012"
      ]
    }



**Html**

  <h2>History Quiz</h2>

<a href="#">Start the Quiz</a>

<h2>Question:</h2>

<ul>
  <li></li>
</ul>

<a href="#">Submit</a>

 <div id="next-question"></div>

  **jQuery**

$(function () {
    var start = $('.start');
    var quiz = $('.quiz');

    var questionIndex = 0;
    var questionData = [];

    start.on('click', function() {
            start.hide();
            quiz.show();
            seeQuestion();
            createRadioButton();
    });

    function seeQuestion() {
        var questions = questionData[questionIndex];

        $('.quiz h2').text(questions.question);//question is viewed in h2
        console.log(questions);

        $('.quiz ul').html(' ');
        //code for the answers
    };

    // create buttons
    function createRadioButton() {
        for (i = 0; i < 5; i++) {
             $('<input type="radio" name="dynradio" />').appendTo('.quiz  ul ');
        };
    };

    $.ajax({
        url: 'https://api.myjson.com/bins/9ocrl',
        dataType: 'json',
        type: 'get',
        cache: false,

        success: function(data) {
             $(data.results).each(function(key, value) {
                 questionData.push(value);
             });
        }
    });
});
Lelo
  • 3
  • 4
  • Possible duplicate of [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Peter B Aug 16 '19 at 12:09
  • console.log(questionData.incorrect_answers); is showing me undefined. What do i need to do for get the right result? – Lelo Aug 16 '19 at 14:01
  • You would have to use something like `questionData[index].incorrect_answers`, with 0 <= `index` <= questionData.length-1. – Peter B Aug 16 '19 at 14:21

1 Answers1

0

Have a look at this snippet.

// data variable that will be "filled" when the
// API request resolves with data
let data

// containers and "active" parts
const question = document.getElementById('question');
const answers = document.getElementById('answers');
const btnNext = document.getElementById('next');

// self calling async function
(async function() {
  // fetching data from the API and waiting for the
  // returned Promise to resolve (or reject)
  // data = await getDataFromAPI()

  // with $.getJSON()
  data = await getJSONData()
  console.log('data', data)
  // activating the next button that is disabled
  // on initial load
  btnNext.removeAttribute('disabled')
})();

// actual function to get data from API
function getDataFromAPI() {
  return new Promise((resolve, reject) => {
    fetch('https://api.myjson.com/bins/9ocrl')
      .then(r => r.json())
      .then(r => resolve(r))
      .catch(err => reject(err))
  })
}

// using $.getJSON() to retrieve data from the API endpoint
function getJSONData() {
  return new Promise((resolve, reject) => {
    jQuery.getJSON('https://api.myjson.com/bins/9ocrl', function(response) {
      resolve(response)
    })
  })
}

// counter - to keep track of current question
var currentQuestionId = 0


// next question code
btnNext.addEventListener('click', function(e) {
  if (data.results.length > currentQuestionId) {

    displayQuestion(currentQuestionId)
    currentQuestionId++
  } else {
    displayFinish()
    currentQuestionId = 0
  }
})

function displayQuestion(questionId) {
  question.textContent = data.results[currentQuestionId].question

  // you can define the answer templates here
  // (e.g. add radiobuttons or something)
  let html = ''
  createAnswers(currentQuestionId).forEach((e, i) => {
    html += `<li>Answer ${i}: ${e}</li>`
  })
  answers.innerHTML = html
}

function displayFinish() {
  answers.innerHTML = ''
  question.textContent = 'You\'ve finished the quiz!'
}

// creating the array for the answers
function createAnswers(questionId) {
  // you can randomize the answer order here (for example)
  return [data.results[questionId].correct_answer, ...data.results[questionId].incorrect_answers]
}
.disabled {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="next" disabled>NEXT</button>

<div id="question"></div>
<ul id="answers">

</ul>

EDIT

The snippet above had to be modified to use $.getJSON() instead of fetch().

I left both solutions in the snippet, but the used / working one is $.getJSON().

Community
  • 1
  • 1
muka.gergely
  • 8,063
  • 2
  • 17
  • 34
  • Thank you, does it work if i replace **data** with my own **questionData** or do i need to create a function to retrive data from the url first? @muka.gergely – Lelo Aug 16 '19 at 18:01
  • I have to edit the answer so it works with your **AJAX** request. – muka.gergely Aug 16 '19 at 18:24
  • OK, now it fetches data from the API you set in your example, waits for it, and then the "NEXT" button activates and you can start with your questions and answers – muka.gergely Aug 16 '19 at 18:37
  • Would appreciate it alot if you could @muka.gergely. I'm reading and watching alot videos and text to try to learn but cant find anywhere. – Lelo Aug 16 '19 at 18:40
  • Thank you from bottom of my heart @muka.gergely – Lelo Aug 16 '19 at 18:41
  • I'm really happy to help :) – muka.gergely Aug 17 '19 at 06:21
  • **var data; $.getJSON('https://api.myjson.com/bins/9ocrl', function(data) { data = data; });** I Get this answer when I try to **console.log(data); Unable to get property 'results' of undefined or null reference.** **How can i do with $.getJSON() like you are doing with fetch? **@muka.gergely – Lelo Aug 17 '19 at 15:09
  • Your problem with `$.getJSON()` seemed to be that you called the response **data** in your function, and that overwrote the **data** variable outside (it was a variable scope problem). I edited the snippet to use the `$.getJSON()` function, but I still do think that you should use `fetch()` instead. The snippet seems to work well with the new function built in. – muka.gergely Aug 17 '19 at 20:29