Based on the JSON structure you provided, we will adjust the PHP backend to read the appropriate format and modify the JavaScript on the frontend to display the quiz data correctly. Here’s how you can set it up:
Step 1: Update the JSON File
Make sure your JSON file (let's name it quiz_data.json) is structured correctly. Based on your example, the content should look like this:
{
"quiz": [
{
"question": "ماذا تعني هذه العلامة المرورية؟",
"question_img": "https://x-iq.com/taw3ia/traffic/1.png",
"answer1": "الاستدارة لليمين الزامية",
"answer2": "تحذير من مفترق طرق غير متحكم فيه",
"answer3": "الزامية اما القيادة للأمام او الاستدارة لليمين",
"answer4": "الانعطاف إلى اليسار إلزامي",
"correct": 3
}
// You can add more quiz objects here
]
}
Step 2: Create the PHP Backend (quiz_reader.php)
Create a PHP file named quiz_reader.php to securely read the JSON file and serve its content:
<?php
header('Content-Type: application/json');
$response = ['success' => false, 'data' => []];
$jsonFilePath = 'quiz_data.json';
if (file_exists($jsonFilePath)) {
$jsonData = file_get_contents($jsonFilePath);
$dataArr = json_decode($jsonData, true);
if ($dataArr !== null && isset($dataArr['quiz'])) {
$response['success'] = true;
$response['data'] = $dataArr['quiz'];
} else {
$response['error'] = 'Failed to decode JSON data or invalid structure.';
}
} else {
$response['error'] = 'JSON file not found.';
}
echo json_encode($response);
?>
Step 3: Update the HTML/JavaScript Code to Fetch from the New JSON Structure
Now, we need to adjust the HTML file, particularly the JavaScript part, to fetch the quiz data and display it according to your JSON structure:
<!DOCTYPE html>
<html lang="ar">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<style>
/* Add your previous styles here */
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
background-color: #f9f9f9;
text-align: center;
}
#output {
max-width: 90%;
width: 90%;
padding: 2%;
border-radius: 10px;
background: white;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
img {
width: 100%;
max-height: 300px;
height: auto;
border-radius: 10px;
display: block;
margin: 0 auto;
}
p {
font-size: 2vw;
color: #333;
margin-top: 1em;
background-color: #eef;
padding: 10px;
border-radius: 5px;
}
.question {
font-size: 2.5vw;
font-weight: bold;
color: #fff;
margin-bottom: 10px;
background-color: #007BFF;
padding: 10px;
border-radius: 5px;
display: inline-block;
word-wrap: break-word;
width: 100%;
}
.loading-bar {
position: relative;
width: 100%;
background-color: #eee;
border-radius: 5px;
height: 10px;
margin-top: 10px;
overflow: hidden;
}
.loading-progress {
height: 100%;
background-color: #007BFF;
width: 0;
transition: width 0.1s ease;
}
</style>
</head>
<body dir="rtl">
<div id="output">
<div class="question-container">
<div class="loading-bar hidden" id="loadingBar">
<div class="loading-progress" id="loadingProgress"></div>
</div>
<div id="content" class="hidden"></div>
</div>
</div>
<script>
// Variables to hold the quiz data
let jsonData = [];
let refreshInterval;
let loadingTimeout;
// Function to load JSON quiz data
function loadQuiz() {
fetch('quiz_reader.php')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.success) {
jsonData = data.data; // Assign loaded data
showRandomQuestion(); // Show a random question
startAutoRefresh(); // Start the refresh timer
} else {
console.error('Error:', data.error);
document.getElementById('output').innerText = 'فشل في تحميل البيانات'; // Arabic for "Failed to load data."
}
})
.catch(error => {
console.error('Error:', error);
document.getElementById('output').innerText = 'فشل في تحميل الملف'; // Arabic for "Failed to load the file."
});
}
// Function to show a random question
function showRandomQuestion() {
if (jsonData.length > 0) {
const randomIndex = Math.floor(Math.random() * jsonData.length);
const questionObj = jsonData[randomIndex];
const questionText = questionObj.question; // Get question
const questionImg = questionObj.question_img; // Get image URL
const answerOptions = [
questionObj.answer1,
questionObj.answer2,
questionObj.answer3,
questionObj.answer4
];
const correctAnswerText = answerOptions[questionObj.correct]; // Get the correct answer
// Show content
const content = document.getElementById('content');
content.classList.remove('hidden');
// Update the output HTML
content.innerHTML = `
<div class="question">${questionText}</div>
<img src="${questionImg}" alt="صورة السؤال" onload="this.style.display='block'"/>
<p>الإجابة الصحيحة: ${correctAnswerText}</p>
<ul>
${answerOptions.map((option, index) => `<li>${option}</li>`).join('')}
</ul>
`;
}
}
// Function to start the auto-refresh timer
function startAutoRefresh() {
refreshInterval = setInterval(() => {
const randomDelay = Math.floor(Math.random() * 5000) + 5000; // Random time between 5 and 10 seconds
startLoadingBar(randomDelay);
setTimeout(showRandomQuestion, randomDelay);
}, 10000); // Refresh every 10 seconds
}
// Function to start the loading bar
function startLoadingBar(duration) {
const loadingBar = document.getElementById('loadingBar');
const loadingProgress = document.getElementById('loadingProgress');
loadingBar.classList.remove('hidden');
loadingProgress.style.width = '0%';
let startTime = Date.now();
loadingTimeout = setInterval(() => {
let elapsedTime = Date.now() - startTime;
let percentage = Math.min((elapsedTime / duration) * 100, 100);
loadingProgress.style.width = percentage + '%';
if (percentage >= 100) {
clearInterval(loadingTimeout);
}
}, 100);
}
// Load the quiz when the script runs
loadQuiz();
</script>
</body>
</html>
Explanation
-
PHP Backend: This script processes the JSON file and returns the quiz data in a structured format. It checks if the file exists and contains valid JSON.
-
HTML/JavaScript:
- It fetches the quiz data from the
quiz_reader.php file instead of an XLSX file.
- The function
showRandomQuestion retrieves a random question, retrieves the question, image, and answers, and then updates the DOM to display the question and answers correctly.
-
Answer Display: The answers are displayed in a list format, and it also shows the correct answer for demonstration purposes.
Conclusion
With these changes, your application now uses a JSON file to serve quiz questions securely via PHP, and it displays the data correctly on the frontend. Adjust the content and arrangement as necessary to fit your design and user experience needs!