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

After making changes to the DOM, the submit button no longer responds when clicked

Currently, I am working on a form that enables users to create a list of items corresponding to a model. In order to enhance user experience, I have incorporated autocomplete functionality for this model. In the relevant controller, I have implemented an ...

Combine several pages from PDF files into a single document

I am currently working on developing a small electron application that combines multiple PDF files or pages into one larger page to help save paper when printing several CAD drawings. Essentially, I am looking for a cross-platform solution similar to the ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Tips for optimizing the sequencing of 3 ajax requests, with the output of one request serving as input for the subsequent two requests

I'm currently working on a solution for chaining 3 ajax calls where the result of one call feeds into the next two. Here's the scenario: // Invoke the ajax calls firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax) ...

The output is displayed in the console, but does not reflect in the browser

I am encountering an issue with my controller while trying to render the results of an AJAX request on my browser. Although I receive the correct html response using Include for Ajax requests, it only shows up in the console and not on the page itself. Wha ...

Testing the Router.push function using Jest and ReactHere is a guide on how

As a beginner in unit testing, I find it challenging to grasp how I can effectively test or mock a push from a router. <Tab label="Members" alt="Members" onClick={() => Router.push('/members')}/> I am particularly concerned about testi ...

Displaying images dynamically in Angular using ng-repeat with URL strings

I'm working on a project where I need to dynamically call pictures inside an ng-repeat loop. Initially, I tried adding a key/value pair of 'img' to the JSON object I'm fetching and then dropping it inside the URL. However, this approach ...

Opinions on crafting a new gadget?

I will only provide each website interested in my widget with the code to copy and paste once. It is crucial that the code is future-proof. After much consideration, this is the widget code I have developed: <script type="text/javascript" src="http:/ ...

Navigate to the homepage section using a smooth jQuery animation

I am looking to implement a scrolling feature on the homepage section using jquery. The challenge is that I want the scrolling to work regardless of the page I am currently on. Here is the HTML code snippet: <ul> <li class="nav-item active"> ...

Developing a specialized directive to enhance bootstrap menuItems

I have created a custom directive in AngularJS for the navbar in Bootstrap. This directive uses ng-transclude and handles two types of list items (li) depending on whether it is a dropdown or not. However, I am experiencing issues with the dropdown functio ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Vue 3 Router view fails to capture child's event

After some testing, I discovered that the router-view component in Vue 3 does not capture events sent from its child components. An example of this scenario is as follows: <router-view @event-test="$emit('new-test-event')" /& ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

JavaScript bug with URL encoding in Internet Explorer 11

I am encountering an issue with Internet Explorer 11 (IE 11) when attempting to call a JavaScript URL function. The problem lies with the URL parameter value, which is in Unicode format but the result displays as ????? instead of Unicode characters. Belo ...

The React app hosted on Firebase displays a message saying "please activate JavaScript to run this application"

I created a web app using React that is hosted on Firebase Hosting, with a backend server utilizing Express and Cloud Functions. You can access the website here: The landing, login, and signup pages are functioning properly. However, when trying to acces ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

What is the best way to store the result from a JavaScript FileReader into a variable for future reference?

I am currently facing an issue uploading a local .json file to my web application. I have managed to display the file in the dev tools, but I am unable to make it accessible for further use. It seems like the problem lies in how I handle (or fail to handle ...

Activate the class using Vue with the v-for directive

I'm curious about the v-for functionality. Why is it necessary to use this.activeClass = {...this.activeClass} to update the component? I noticed that the component does not update after this line of code. if (this.activeClass[index]) { ...