Is there a way to verify if a user has selected the correct answer in a quiz program?

Here we have code segments in ajax, javascript, html, and an xml file.

I'm looking to calculate the total score based on user input to determine if they selected the correct answers for a test. I've attempted to figure this out, but I'm struggling with developing the necessary code to solve this issue.

Any advice would be highly appreciated. Thank you for taking the time to read this.

This snippet includes javascript and ajax.

var score;
var i;

function loaddata() {

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
 // r = xhr.JSONparse(responseText);
  displayData(xhr);
 }
};
xhr.open("GET", "FinalQuiz.xml", true);
xhr.send();
}

function displayData(xhr) {
console.log(xhr);

// Retrieving data as an xml file
var xmldoc = xhr.responseXML;
// Begin table
var output="";
// Process data by record
var x = xmldoc.getElementsByTagName("question");

for(i = 0; i<x.length; i++)
{
output+="Question ";
output+=x[i].getElementsByTagName("qnumber")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+="Title: ";
output+=x[i].getElementsByTagName("qtitle")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+= "<button onclick=\"answer()\">A</button>" ;
output+=x[i].getElementsByTagName("a")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+= "<button onclick=\"answer()\">B</button>" ;
output+=x[i].getElementsByTagName("b")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+= "<button onclick=\"answer()\">C</button>" ;
output+=x[i].getElementsByTagName("c")[0].childNodes[0].nodeValue + " ";
output+="<br>";
output+= "<button onclick=\"answer()\">D</button>" ;
output+=x[i].getElementsByTagName("d")[0].childNodes[0].nodeValue;
output+="<br>";
output+="<br>";
}
document.getElementById("quiz").innerHTML = output;
}

function answer()
{
score = score + 1;
}

The following is the xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE finalquiz SYSTEM "FinalQuiz.dtd" >
<finalquiz>
... [XML content here]
</finalquiz>

This corresponds to the html file.

[HTML content here]

Answer №1

It appears that there are numerous issues with the program's logic.

First and foremost, it seems like this may be a learning opportunity for you as having answers within the same XML file being rendered on the client side is not secure (they can easily be viewed using developer tools).

Additionally, the algorithm used lacks depth and logic in the code.

When calculating scores, two main factors to consider include:

1) The answer chosen for each question

2) What happens if the user changes their answers

In handling these aspects, choosing an appropriate data type to store answers is crucial. I would suggest using a JavaScript object.

In this object, the keys represent question numbers while the values indicate individual scores. Initially, all scores are set to zero and adjusted accordingly based on correct or incorrect answers.

var score = 0;
var result; // contains correct answers from the XML
var answered = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}; // question number key, individual score value

Rather than simply recording answers, the answer() function should track which question is being answered and what choice is made. This can be achieved by modifying it to answer(i, 'a'), answer(i, 'b'), etc., where i represents the question index (starting at 0) and the second parameter signifies the option selected.

Ultimately, the logic within the answer function should resemble:

function answer(i, ans)
{
  var ansArray = result[0].innerHTML.split(",");
  answered[i] = ansArray[i] == ans ? 1 : 0;console.log(answered);
  score = answered[0] + answered[1] + answered[2] + answered[3] + answered[4];
  //alert(score);
}

View Working Demo 1

Explore Working Demo 2

P.S: This is just one approach among many for addressing the issue raised in the original post.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

How can I navigate between pages without losing the data entered in the form fields

Is there a way in Ajax or jQuery to save form data and navigate between multiple form pages without using PHP Sessions? I want the form data to be saved until the user submits it, and when they do submit, all information from different pages should be in ...

What are the steps for configuring a dynamic variable?

One issue I encountered was setting up a variable in vue that updates when the screen orientation changes. Despite adding this variable to the data object, it did not become reactive as expected. This is my initial data function for the component: data() ...

JavaScript form not working on submission

When my form is submitted, a function is called that successfully redirects users on desktop to either the download-confirmation or download-failure page. However, when testing on mobile devices such as iOS and iPad, the redirection does not seem to work. ...

Struggling to transfer a specific row from a grid to a fresh window in extjs

My goal is to send the selected row from a grid panel to a new window when the user clicks the edit button or double-clicks the row. However, I am encountering difficulties in sending the data. Below is the code for my grid panel (List.js): Ext.define(&a ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Is anyone else experiencing issues with the jQuery slide-in not working on a particular website? How can I determine which version of jQuery is compatible with this site?

Essentially, I am looking to have a div box slide in on the page as it loads. This method has worked successfully on other websites and HTML previews that I have tested it on so far. However, for some reason, it does not seem to work on this specific websi ...

Unusual navigation patterns in Angular

https://i.sstatic.net/kdh4A.png My Mean app is set up with the Angular app residing in the '/dashboard' path. The home page of the app works fine. Reloading the app returns the page it was on. Even routes with '/dashboard/anything/anything& ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...

Divide using two separators

const inputString = 'db.employee.find({"city":"Paris"},{"emp_id":1}' const result = inputString.split(/\.|\[); // splitting based on . or [ Is there a way to split a string based on two delimiters, such as . and [? For example, if we ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

CSS2DRenderer Reset Feature

My scene, camera, renderer, and CSS2DRenderer are created using this class. I am looking for a way to reset (delete and add again) my CSS2DRenderer in order to remove any previously rendered CSS2DObject. Can you guide me on how to achieve this properly? T ...

Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

The jQuery mousedown() function seems to be malfunctioning and unable to trigger the drag event

I am attempting to initiate a drag event using jQuery. You can access the fiddle by clicking here http://jsfiddle.net/sgsvenkatesh/hepbob75/5/ I tried using the following code to initiate the drag event, but it doesn't seem to be working: $(documen ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

Can we stub these types of functions in any manner?

One file named helperFunction.js contains the following code: module.exports = (arg1, arg2) => { \\function body } To use this function in another file named file.js, you can simply call it like this: let helperFunction = require(' ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

Nested Views in Angular UI Router

I have a specific structure set up like this: <div ui-view="main"> <!-- content is dynamically loaded here by AngularJS ui-router --> <aside ui-view="sidebar"> <!-- sidebar content is also populated by AngularJS ui-router --&g ...