Enter a nickname, which will appear in the leaderboard table and a random email (can be fake, we are not using them in this example)
The quiz needs to have a form with at least 2 fields when you re-create the leaderboard using our sample code. It is important for the field lables to be:
The screenshot below shows how to name your formfields:
The leaderboard needs to get data from 2 different sources:
All quiz scores are sent to a MySQL database using the Riddle webhook. As the webhook is getting the data with a few minutes delay after the quiz is finished, it won't be able to include the current quiz takers score when the leaderboard is first displayed. Therefore the quiz score from the current quiz taker is captured using JavaScript Events and sent to the leaderboard page via a session cookie.
To store the leaderboard data in a database, you need to send the Riddle data to a webhook endpoint. Start by creating a new PHP file on your webserver and add the URL of that file to Riddle. You can learn more about using webhooks here
Place the code below on the page where you embedded your Riddle.
The code below uses session cookies. Instead of session cookies you could also send the data to the custom result page via POST variables, but session cookies provide an easier way as many webservers block the receipt of POST vars.
<script>
// Clear the session cookies on page load
document.cookie = "Nickname=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
document.cookie = "Email=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
document.cookie = "ResultScore=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
window.addEventListener("message", function(event) {
var eventData = event.data;
// Check for Form_Submit action
if (eventData.action === "Form_Submit" && eventData.answer) {
var answerParts = eventData.answer.split(':::');
var Nickname, Email;
// Loop through the answerParts to find Nickname and Email
for (var i = 0; i < answerParts.length - 1; i++) {
var segment = answerParts[i].split('::');
if (segment.length > 2) {
if (segment[1].trim() === "Nickname" && !Nickname) {
Nickname = segment[2].trim();
} else if (segment[1].trim() === "Email" && !Email) {
Email = segment[2].trim();
}
}
}
// Store the values in session cookies
if (Nickname) {
document.cookie = "Nickname=" + Nickname + "; path=/;";
}
if (Email) {
document.cookie = "Email=" + Email + "; path=/;";
}
}
// Check for CoreMetrics action and Finish name
if (eventData.action === "CoreMetrics" && eventData.name === "Finish") {
var resultScore = eventData.resultScore;
// Store the resultScore in a session cookie
document.cookie = "ResultScore=" + resultScore + "; path=/;";
}
});
</script>
As mentioned above, you need to process the quiz data and store it in a MySQL Database on your server. The code below will wait for the Riddle webhook, extract the email, nickname and quiz score and store the data in a table in your database. For the code to work, you need to create a table with the correct column names. You can use the SQL to create the table with the fields that the sample code uses:
CREATE TABLE leaderboard ( id INT(11) NOT NULL AUTO_INCREMENT, nickname VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, score INT(11) NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY (email) );
<?php
function logToFile($message) {
$logFile = "webhook_log.txt"; // Specify your log file name
file_put_contents($logFile, date("Y-m-d H:i:s") . " - " . $message . "\n", FILE_APPEND);
}
// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the raw POST data
$rawData = file_get_contents('php://input');
logToFile("Received Payload: " . $rawData);
// Decode the JSON data
$jsonData = json_decode($rawData, true);
if (json_last_error() !== JSON_ERROR_NONE) {
logToFile("JSON Decode Error: " . json_last_error_msg());
}
// Check if decoding was successful
if ($jsonData) {
// Extract the necessary values
$nickname = "";
$email = "";
$score = 0;
// Extract Nickname
if (isset($jsonData['data']['form'][0]['value'])) {
$nickname = $jsonData['data']['form'][0]['value'];
logToFile("Assigned Nickname: " . $nickname);
}
// Extract Email
if (isset($jsonData['data']['form'][1]['value'])) {
$email = $jsonData['data']['form'][1]['value'];
logToFile("Assigned Email: " . $email);
}
// Extract Score
if (isset($jsonData['data']['result']['score'])) {
$score = $jsonData['data']['result']['score'];
logToFile("Assigned Score: " . $score);
}
// Database connection details - make sure to enter the correct data to connect to your DB below
$host = 'localhost';
$db = 'dbname';
$user = 'dbuser';
$pass = 'dbpass';
$charset = 'utf8mb4';
// Create a new PDO instance
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
// Prepare an INSERT statement
$stmt = $pdo->prepare("INSERT INTO leaderboard (nickname, email, score) VALUES (?, ?, ?)");
// Execute the statement with the extracted values
$stmt->execute([$nickname, $email, $score]);
logToFile("Data received, processed, and stored in the database.");
} else {
logToFile("Failed to decode JSON data.");
}
} else {
logToFile("Invalid request method.");
}
?>