0

I'm learning JS and working on a trivia app that is using questions from https://opentdb.com. I'm having trouble making the API call to generate questions based on a selected category and difficulty. I'm using Jquery/Ajax library to connect to API however it's giving me a parse error. I'm having trouble understanding how to properly do it, Over the past few days I've read a ton of documentation on this and I'm struggling to grasp the concept. I tried doing it with vanilla JS (fetch(), etc., and was unsuccessful. If anyone could lend an eye and suggest where I'm going wrong I'd appreciate it.

My code so far:

const score = document.querySelector('#score');
const output = document.querySelector('#output');
const answerSelect = document.querySelector('#selAnswers');
const btn = document.querySelector('#btn');

const categories = [
  'Sports',
  'Art',
  'Vehicles',
  'History'
];

const difficulty = [
  'easy',
  'medium',
  'hard'
];

btn.addEventListener('submit', function(e) {
  e.preventDefault();

});

document.addEventListener('DOMContentLoaded', function() {

  let categorySelect = document.querySelector('#category');
  let difficultySelect = document.querySelector('#difficulty');

  let html = '';
  for (let item of categories) {
    // Appending Strings created using Template literals
    html += `<option>${item}</option>`;
  }
  categorySelect.innerHTML = html;

  for (let item of difficulty) {
    let opt = document.createElement('option');

    // <option> will use its .textContent as value if not explicitly defined
    opt.textContent = item;

    difficultySelect.append(opt);
  }
});

$.ajax({
  url: 'https://opentdb.com/api.php?amount=10',
  data: {},
  type: 'GET',
  dataType: 'jsonp',
  success: function(data) {
  },
  error: function(jqXHR, textStatus, ex) {
    console.log(`${textStatus}, ${ex}, ${jqXHR.responseText}`);
    alert(`${textStatus}, ${ex} ${jqXHR.responseText}`);
  }
});


//function

function getQuestion() {

  result.innerHTML = '';
  btn.innerHTML = '';

  let categoryOption = categories.value;
  let difficultyLevel = difficulty.value;
}
<!doctype html>
<html lang="en">

<head>
  <title>Trivia</title>
  <link rel='stylesheet' href='css/Trivia.css'>
</head>

<body>
  <h1>Trivia</h1>
  <div>Score: <span id="score">Correct 0 Wrong 0</span></div>
  <br>
  <div>
    <label>Select Category:</label>
    <select id='category'></select>
    <br>
    <label>Select Difficulty:</label>
    <select id='difficulty'></select>
  </div>
  <br><br>
  <div id="output"></div>
  <br>
  <div id="selAnswers"></div>
  <br>
  <button id="btn">Get First Question!</button>
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src='js/Trivia.js'></script>
</body>

</html>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1raf
  • 57
  • 4

0 Answers0