Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Help with JavaScript and AJAX

Hi,

I'm trying to apply some of what I learned about JavaScript and AJAX by making my own trivia game from scratch. However, I'm not getting the behaviour I expected from my code. When I preview, I get an error that my questions variable does not exist; I'm also apparently not getting to my readystate === 4 in my if statement.

For context, I have a JSON file of trivia questions, and I am trying to be able to use that list so I can pull out questions to display to the user.

My Workspace is here: https://w.trhou.se/1dishlso3b

Here's my scripts.js file right now:

// Initializes the game
function initialize() {
  var questionCounter = 0;
  var score = 0;
  var wrongAnswers = 0;
  var questions = [];
  console.log(questions);
  buildQuestionList();
  console.log(questions);
  drawGameInterface();
};

// get the list of questions 
function buildQuestionList() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        var questionsJSON = JSON.parse(xhr.responseText);
        questions.push(questionsJSON);
        alert("In the JSON if statement");
      } else {
        document.getElementById('questionDiv').innerHTML = "<p>There has been an error.</p>";
        console.log("In the JSOn else statement");
      }
    }
  xhr.open('GET', 'questions.json');
  xhr.send();
};

//draw the game interface 
function drawGameInterface() {
  $("#welcome").toggle("slow");
  $("#answerDiv").toggle("slow");
  $("#scoreDiv").toggle("slow");
};

// hides the placeholder text when user clicks in the answer box-sizing
$("#answer").focus(function() {
  $("#answer").val("");
});

I'd love any help you can provide!

Hi David,

Your workspaces link doesn't work. You have to take a Snapshot of your workspace and then post that link. Here's some instructions.

2 Answers

Whoops! Thanks--fixed now.

https://w.trhou.se/1dishlso3b

jag
jag
18,266 Points

Here are some things I noticed:

  1. Extra closing body tag
  2. Didn't close ul tag for .wrongResponses
  3. Since you are using Ajax might as well use $.getJSON()
  4. If you check your browsers console an error saying question is undefined which breaks your whole code
function buildQuestionList() {
  $.getJSON('questions.json', function (data){

  $.each(data, function(key, val){
    console.log(val.question);
    console.log(val.answer);
  });
  });
};
jag
jag
18,266 Points
// Initializes the game
function initialize() {
  var questionCounter = 0;
  var score = 0;
  var wrongAnswers = 0;
  var questions = [];
  console.log(questions);
  buildQuestionList();
  console.log(questions);
  drawGameInterface();
};


// get the list of questions
function buildQuestionList() {
  $.getJSON('questions.json', function (data){

  // Store Q&A in Arrays
  var questions = []
  var answers = []
  var i = 0
  $.each(data, function(key, val){
    // Adds questions to question array
    questions.push(val.question);
    // Adds answers to answers array
    answers.push(val.answer);
  });
  // console.log(questions[i] + "Questions")


  // Loop forever until condition is met
  do {

     // Ask user a question, remove hint just testing purposes
     var response = prompt(questions[i], 'hint it is' + answers[i])
     console.log(i < questions.length);

     // User gets it right then treated unto the next question
     if(response === answers[i]){
     console.log('correct, next question')
     // Goes to next item in Q&A Arrays
     i++

   }else if(response === "end"){
     // User can give up by entering end
     console.log("This ends now.")
     break;
   }else{
     // User gets wrong answer, send message
     console.log('wrong, till you get it right')
     }
    // Condition while the array has enough question, quiz will keep looping
  } while(i < questions.length)


  });

};


//draw the game interface
function drawGameInterface() {
  $("#welcome").toggle("slow");
  $("#answerDiv").toggle("slow");
  $("#scoreDiv").toggle("slow");
};



// hides the placeholder text when user clicks in the answer box-sizing
$("#answer").focus(function() {
  $("#answer").val("");
});

// display a question
/*
function getQuestion() {
    $("#answer").val("My Answer Is...")
          console.log(questions[0].category);
          questionHTML = "<p>" + questions[0].question + "</p>"
          document.getElementById('questionDiv').innerHTML = questionHTML;
      }
    };

};

// get the user's answer

$("#answerForm").submit(function(){

  event.preventDefault();
  var userAnswer = $('#answer').val().toLowerCase();
  var correctAnswer = questions[0].answer;
  if (userAnswer === correctAnswer) {
    score++;
  } else {
    $(".wrongResponses").append("<li>&#10006;</li>")
    wrongAnswers++;
    if (wrongAnswers === 3) {
      $("#welcome").toggle("slow");
      $("#answerDiv").toggle("slow");
      $("#scoreDiv").toggle("slow");
    }
  }


})

// check if the answer is correct

// adjust the score
*/

Here is the quiz using Arrays, for while loop, prompt & getJSON. If you need any help feel free to ask.