0

On the Javascript part you see how the score is calculated and how it will be display on the site, but i want the score that comes out inserted my flask app. So I'm able to insert the score into my MySql database. Sorry for my bad English.

Javascript:

// Computes score and returns a paragraph element to be displayed
        function displayScore() {
            var score = $('<p class="quizvraag">', {id: 'question'});

            var numCorrect = 0;
            for (var i = 0; i < selections.length; i++) {
                if (selections[i] === questions[i].correctAnswer) {
                    numCorrect++;
                }
            }

            score.append('You got ' + numCorrect + ' questions out of ' +
                    questions.length + ' right!!!');


            return score;
        }`

Flask:

@app.route('/quiz')
def quiz():
startquiz()

DbLayer = DbClass()
vragen = DbLayer.getQuizVraag()
list_vraag = [vragen]
print(vragen)
return render_template('quiztestjs.html', vraag=vragen, list_vraag=list_vraag)

MySql query:

    def setDataToDatabase(self, Score1):
    # Query met parameters
    sqlQuery = "INSERT INTO tbl_score (Score1) VALUES ('{param1}')"
    sqlCommand = sqlQuery.format(param1=Score1)

    self.__cursor.execute(sqlCommand)
    self.__connection.commit()
    self.__cursor.close()

1 Answers1

0

There are multiple ways to do this, depending on how much of your "business logic" running in the client you are comfortable with.

You could just send the calculated score back via JavaScript using XMLHttpRequest (Send POST data using XMLHttpRequest), and save it to your DB.

However, consider the implications, particularly the fact that the client is then fully responsible for deciding on the quiz result and score.

A player might just cheat on your quiz, as they have all the data, or they might forge the request and just send whatever score they want.

A better approach, in my opinion, would be to have just the questions presented to the user, and the decision if correct or incorrect being handled on the server, as well as score calculation.

A possible implementation could have:

GET /quiz - present questions

POST /quiz - submit answers, render result to user, write score

As in, the GET request will render a form with the questions and answers, and the submit action for that form will POST to the same (or different if you prefer) URL, where you retrieve the form data (Sending data from HTML form to a Python script in Flask).

The point of all that being that the information what answers are the correct ones is not shared with the client before they submit and get their result.

bgse
  • 8,237
  • 2
  • 37
  • 39