Advertisement
MartinYanchev-99

quiz.js

Mar 15th, 2021
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const url = window.location.href
  2.  
  3. const quizBox = document.getElementById('quiz-box');
  4. $.ajax({
  5.     type: 'GET',
  6.     url: `${url}data`,
  7.     success: function(response) {
  8.         //console.log(response)
  9.         let data = response.data;
  10.         data.forEach(el => {
  11.             for (const [question, answers] of Object.entries(el)) {
  12.                 quizBox.innerHTML += `
  13.                 <hr>
  14.                 <div class="mb-2">
  15.                     <b> ${question}</b>
  16.                 </div>
  17.                
  18.                 `
  19.                 answers.forEach(answer => {
  20.                     quizBox.innerHTML += `
  21.                         <div>
  22.                             <input type="radio"
  23.                                 class="ans"
  24.                                 id="${question}-${answer}"
  25.                                 value="${answer}" name="${question}">
  26.                                 <label for="${question}-${answer}">${answer}
  27.                                 </label>
  28.                             </input>
  29.                    
  30.                     </div>
  31.                 `
  32.                 })
  33.             }
  34.         })
  35.     },
  36.     error: function(error) {
  37.         console.log(error)
  38.     }
  39. })
  40.  
  41. const quizForm = document.getElementById('quiz-form');
  42. const csrfToken = document.getElementsByName('csrfmiddlewaretoken')
  43. const elements = [...document.getElementsByClassName('answers')];
  44. const sendData = () => {
  45.     const data = {};
  46.     data['crsfmiddlewaretoken'] = csrfToken[0].value
  47.     elements.forEach(el => {
  48.         if (el.checked) {
  49.             data[el.name] = el.value;
  50.         } else {
  51.             if (!data[el.name]) {
  52.                 data[el.name] = null;
  53.             }
  54.         }
  55.     })
  56.  
  57.     $.ajax({
  58.         type: 'POST',
  59.         url: `${url}save/`,
  60.         data: data,
  61.         success: function(response) {
  62.             console.log(response)
  63.         },
  64.         error: function(error) {
  65.             console.log(error)
  66.         }
  67.     })
  68. }
  69. quizForm.addEventListener('submit', e => {
  70.     e.preventDefault()
  71.     sendData()
  72. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement