Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Triva with AJAX

In this activity, we’ll make AJAX calls of a back-end to play trivia without reloading the browser page. Specifically, we’ll make use of XMLHttpRequest to complete the AJAX call.

Start by creating a new triviajs.html file with the starter code below. We’ve provided some JavaScript functions to handle user interaction and verifying the user’s answer.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">  
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Trivia Game AJAX</title>

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> 
    </head>

    <body>


        <div class="container" style="margin-top: 15px;">
            <div class="row col-xs-8">
                <h1>CS4640 Television Trivia Game - AJAX Edition</h1>
                <h3>Score: <span id="score">0</span></h3>
            </div>
            <div class="row">
                <div class="col-xs-8 mx-auto">
                <form>
                    <div class="h-100 p-5 bg-light border rounded-3">
                    <h2>Question</h2>
                    <p id="question_text"></p>
                    </div>

                    <div id="message"></div>
                    
                    <div class="h-10 p-5 mb-3">
                        <input type="text" class="form-control" id="answer" name="answer" placeholder="Type your answer here">
                    </div>
                    <div class="text-center">                
                    <button class="btn btn-primary" onclick="checkAnswer(); return false;">Submit</button>
                    </div>
                    
                </form>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>

        <script>
            var question = null;
            var score = 0;

            function getQuestion() {
                // instantiate the XMLHttpRequestobject
                
                // open the request
                
                // ask for a specific response (set responseType = "json" since we are
                // expecting a JSON object
                
                // send the request
                
            
                // What happens if the load succeeds
                
            
                // What happens on error
                
            }
        
            // Method to display a question
            function displayQuestion() {
                // Why innerHTML and not textContent?
                document.getElementById("question_text").innerHTML = question.question;
            }

            function checkAnswer() {
                var answer = document.getElementById("answer").value;

                document.getElementById("answer").value = "";

                if (question.answer == answer) {
                    // got it right
                    score += 10;
                    document.getElementById("score").textContent = score;
                    document.getElementById("message").innerHTML = 
                        "<div class='alert alert-success'>Correct!</div>";
                    setTimeout(function() {
                        document.getElementById("message").innerHTML = "";
                        getQuestion();
                    }, 5000);
                } else {
                    // got it wrong
                    // to do 
                    document.getElementById("message").innerHTML = 
                        "<div class='alert alert-danger'>Incorrect!</div>";
                    setTimeout(function() {
                        document.getElementById("message").innerHTML = "";
                        getQuestion();
                    }, 5000);
                }
            }
            
            // Need to add the initial question load
            
            
            
            
        </script>
    </body>
</html> 

Add AJAX

Follow the comments in the getQuestion() function to instantiate an XMLHttpRequest object, open and send the request to the backend below, then add event listeners for “load” (everything works) and “error” events.

https://cs4640.cs.virginia.edu/activities/triviajs.php

Event Handlers

load: If the AJAX request succeeds (i.e., check that the HTTP response code was 200), then save the response in a variable and use the displayQuestion() function to display the question to the user.

error: If the AJAX request fails, then update the element with id message to include an error to the user. You should use Bootstrap to style this error.

Submission

Submit your triviajs.html on Gradescope in today’s activity submission form. If you worked in a group, please submit once for the entire group, but be sure to include everyone in the Gradescope submission.

The Gradescope submission will remain open until Friday night.