Call getElementById upon the successful completion of an AJAX request

In the process of constructing a mini quiz, I am utilizing a variable quizScore to store the score. Each question in the quiz is displayed using AJAX. An individual AJAX call captures the ID of the button pressed (for example, on question 2, the button ID is 2a which leads to the subsequent AJAX refresh of question2a.php).

During the final AJAX call, when questionendQuiz.php is summoned, I aim to display the value of the variable quizScore. It is crucial to bind this output to an event ensuring that the loading of this data through AJAX is successful.

/* Outputting the score */
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
    document.getElementById("quizWrapper").innerHTML=xmlhttp.responseText;
    if (buttonID == "question_endQuiz") {
        document.getElementById("scoreOut").innerHTML = quizScore;
    }
}

Hence, upon the triumphant AJAX content load, the quizScore should be displayed in div id="scoreOut".

After verifying the functionality of the scoring system through console logs, I can confirm that it correctly tallies the score (you can view it displaying the score here:

I am perplexed as to why the success condition is failing to showcase the score?

The following script provides only relevant information for this inquiry, omitting extraneous details like correct answer validation and quiz initiation:

/* Quiz Scoring Mechanism */
var quizScore = 0; /* Advances to the subsequent question based on ButtonID */

function nextQuestion(buttonID) {
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
        }
    }
    var splitID = buttonID.split('_');
    var questionID = splitID.pop();
    xmlhttp.open("GET", "question" + questionID + ".php", true);
    xmlhttp.send(); /* Outputting the score */
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
        if (buttonID == "question_endQuiz") {
            document.getElementById("scoreOut").innerHTML = quizScore;
        }
    }
}

The button signaling the conclusion of the quiz is:

<button id="question_endQuiz" onClick="nextQuestion(this.id)">See your score</button>

Answer №1

The part where the score is recorded should also be included in the onreadystatechange function. This function serves as the request callback, executing after receiving the response rather than before, as shown in your code sample.

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
            if (buttonID == "question_endQuiz") {
                document.getElementById("scoreOut").innerHTML = quizScore;
            }

        }
    }

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

I am having trouble getting Google Maps to load

Why does the map on my website only load when the browser window is resized? Below is the JavaScript code being used: <div class="map-cont"> <div id="map" class="location-container map-padding" style="width:100%;height:400px;background:y ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon. @Directive({ selector: '[appDatepicker]' }) export class DatepickerDirective implements DoCheck{ constru ...

Only a singular operation is carried out

Contained within my .js file are two functions: function download510(form) { if (form.pass.value=="tokheim") { location="../pdf/quantium-510.pdf" } else { alert("Invalid Password") } }; function download410(for ...

Send the result of a successful AJAX request to a partial view

I have added these lines of code, where the success function returns data in the form of [object Object], with attributes like Name, Category, and Description. $.ajax({ url: rootUrl + 'Admin/EditRSS', type: "GET", data: { ...

Error encountered using Meteor 1.3 autoform/quickform integration

Having recently transitioned to using Meteor 1.3, I've encountered a few challenges related to debugging due to missing imports or exports in tutorials. This particular issue seems to be in the same vein. I wanted to incorporate the autoform package ...

Incorporate a pseudo class to a unique custom template or directive within an Angular project

I have been developing a custom dropdown menu directive in AngularJS. The issue I'm facing is that the buttons in my template become inactive when interacting with the dropdown menu, unlike a regular HTML select which remains active while the dropdown ...

Implementing custom click event for selecting checkboxes in Material-UI table rows

I have been working with the material-ui data table to implement sorting functionality. One feature I am trying to add is a checkbox on each row. The challenge I am facing is that when clicking on the checkbox, it also triggers the row link, which is not t ...

nuxt-link: take me to the identical position with the hash in the URL

I'm facing an issue with the <nuxt-link> component in my Nuxt application: The first time I click on the link, everything works perfectly and the page is changed as expected. However, if I scroll down a bit and try clicking the link again, noth ...

It is not possible to change the maximum height of a Popover in Material UI

I am currently working with the Popover component in material-ui, but I am facing an issue modifying the max-height property that is calculated as max-height: calc(100% - var). I have attempted different solutions such as using className and override, but ...

What is the mechanism through which a nested function within an event handler obtains the event object?

How is the e object available to the nested function inside handleClick2 when only the input object is passed? Is this related to the concept of Lexical Environment? handleClick2 = (input) => (e) => { this.setState({ [input]: e.target.va ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

Exploring the Differences Between Meteor JS Backend and Express JS

I have a basic understanding, but I'm interested in learning more: I came across a comparison on Stack Overflow that likened Meteor JS and Express JS to oranges and potatoes. My current understanding is that Meteor JS is full stack (Front End, Back E ...

What is the technique for invoking methods of the Joi class without the need to instantiate an object?

I recently delved into using the Joi NPM module and found it confusing that although it is described as a class in the documentation, it does not require creating a class object like var joi = new Joi();. Can you explain how this works? My understanding o ...

Send the user to the codeigniter controller with a click

Is there a way to redirect a user to a different page when they click on a specific division element? I am looking for guidance on how to redirect the user to CI's new controller from an HTML view. Thank you in advance. ...

Hiding validation messages upon clicking in a textbox in ASP.NET MVC: a tutorial

When attempting to hide the validation message on click of the textbox, it remains visible. Can someone please provide assistance? <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @autoco ...

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance. ...

How can serial numbers be sorted using a JavaScript If Statement based on 2 criteria?

I'm currently enrolled in a JavaScript coding course where I am tackling a task involving validating serial numbers. The requirement is to check if a serial number is valid and then add it to an array to store all the valid serial numbers. The criteri ...

What is the best way to save a jQuery or JavaScript variable into a JSON file?

Is there a way to save a jquery variable in a json file? I have the following: var image='/test/test.png'; I am obtaining this path through file upload: <input type="file" name="imageurl" value="imagefile"></input> Therefore, I ne ...