Francesca
Francesca

Reputation: 28168

Output Javascript variable when page loads through AJAX

I have a quiz where each question reloads in a div using AJAX rather than refreshing the entire page.

I have a variable quizScore which holds the score the user has.

On the last button press, the page questionendQuiz.php is loaded into my quizWrapper.

I want to output the score into a span called scoreout

<span id="scoreOut"></span>

I tried using getElementById

document.getElementById("scoreout").value = quizScore;

The problem is, this doesn't run when the page is loaded in through AJAX. So I tried binding it to the success of the AJAX page loading:

$( document ).ajaxComplete(function( event,request, settings ) {
  document.getElementById("scoreout").value = quizScore;  
});

So that when the page with that script on is run it should run and output the score, but it doesn't seem to work.

You can see the site here: http://fh80.student.eda.kent.ac.uk/fyp-assets/quiz/quiz.php

Upvotes: 0

Views: 42

Answers (2)

vortexwolf
vortexwolf

Reputation: 14037

I looked at your website. In order to make it work, you should change your nextQuestion function and add if(buttonID ... like this:

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

Also it should be "scoreOut" instead of "scoreout" because javascript is case-sensitive.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707876

.value is for form elements like <input> tags. You should use .innerHTML for a div or span or other type of HTML element.

document.getElementById("scoreout").innerHTML = quizScore;

As for the timing issue, you just need to execute this statement AFTER the scoreout DOM object is in the page and the quizScore is at its current value. This doesn't permanently bind the value of quizScore to the DOM element, it's just a one time transfer of the value. You will have to rerun this statement anytime you want to display the newly changed score.

If you are updating this score via an ajax call, you can either use .ajaxComplete() as you are doing to update the score after any ajax call completes or you can update the score display in your code right after you calculate the newly updated score (wherever that is in your code).

Upvotes: 2

Related Questions