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

Finding the inverse value from the Lodash get() function

My current approach involves utilizing the lodash get() method to retrieve values from an object. However, there are instances where I need to obtain negated values. Unfortunately, simply applying a negate symbol or negate method after retrieving the valu ...

Issue with vue-cli3 eslint and compiler arising from conflicting vue/script-indent settings

Whenever my .eslint.js file includes this rule: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, } ] and I save it, an error pops up: Error: Expected indentation of 32 spaces but only found 24 spaces ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

I'm curious if there is a method in Next.js to dynamically replace all `<a>` tags within nested components in order to prevent full page refreshes

Our client requires the use of a React component library that offers various layout components such as Header/Footer elements and Navigation menus. However, only the href string value can be passed for navigation items, preventing any manipulation during r ...

The principle of event delegation in jQuery

Are event handlers delegated across both <div> tags? In other words, is there one or two event handlers being used? I'm looking to extract the data-id from the event.delegateTarget. It's straightforward when attached to each of the <div& ...

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Retrieving information from an object using a randomly generated identifier

Imagine having an object structured like this. var foo = { "dfsghasdgsad":{ "name":"bob", "age":"27" } }; The variable foo will consistently only have one object, but the key is dynamically created. How can I access the values "bob" and "27" ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

struggling to transfer information from JavaScript to Jade within the Node.js environment

Currently, I am retrieving a row from a Cassandra table called "emp". My objective is to pass the data retrieved from the JavaScript file to a Jade file in order to display this information on the user interface. In my JavaScript function: router.get(&a ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

Displaying JSON data in an HTML table cell format

Hey everyone, I need some help with the following task: I am working on displaying a list of log lines in an HTML table. Some of these lines will contain JSON strings, and I want to format the JSON data within the table when the HTML file is loaded from ...

Setting up the InMemoryCache in Vue ApolloConfiguring the InMemoryCache

I've set up vue-apollo following the instructions in the apollo.config.js file from this guide: (I'm using VSCode). Now, I want to configure the InMemoryCache to exclude the typeName (addTypename: false) like it's explained here: https://w ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Retrieve the v-id-xx attribute value for scoped styling in a Vue Single File Component

When using pure JavaScript to add elements in a Vue Single File Component, the added elements are missing the v-id-xx attribute for scoped CSS. Is there a way to retrieve the component's v-id-hash value using only JavaScript? ...

Utilizing AJAX to send an array of data in JSON format

I have successfully extracted specific elements from a form, stored them in an array and now want to convert this array into a JSON object to send it to a PHP file via AJAX. However, I am facing some issues with my code. Here's what I have done so far ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

Guide on retrieving the innerHTML of all <a> tags within a specific span class

<span class="mgen"> <a rel="tag">Action</a> <a rel="tag">Adventure</a> <a rel="tag">Apocalypse</a> <a rel="tag">Fantasy</a> <a rel="tag" ...