Claro! Vou te entregar uma versão completa e corrigida, para o arquivo principal nivelamento.php que exibe o quiz interativo, e o arquivo processar_respostas.php que processa as respostas via AJAX e retorna JSON.
1) nivelamento.php (quiz interativo, um por vez, com progresso e popup resultado)
<?php
session_start();
require_once 'includes/db.php';
// Apenas estudantes autorizados
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
header("Location: login.php");
exit;
}
// Perguntas corrigidas (vírgulas corrigidas)
$questions = [
1 => ["What’s your name?", ['a' => 'How are you?', 'b' => 'My name is John.', 'c' => 'I am fine.']],
2 => ["Where do you live?", ['a' => 'In São Paulo.', 'b' => 'I’m 25 years old.', 'c' => 'I have a dog.']],
3 => ["What time is it?", ['a' => 'I like pizza.', 'b' => 'I go to work.', 'c' => 'It\'s 3 PM.']],
4 => ["Choose the correct verb: 'She ___ to school.'", ['a' => 'goes', 'b' => 'go', 'c' => 'going']],
5 => ["What’s the past tense of “eat”?", ['a' => 'eating', 'b' => 'ate', 'c' => 'eaten']],
6 => ["I have been ____ English for 2 years.", ['a' => 'learn', 'b' => 'learned', 'c' => 'learning']],
7 => ["Which is correct?", ['a' => 'There is a book on the table.', 'b' => 'There are a book.', 'c' => 'There is books.']],
8 => ["Synonym of 'big'?", ['a' => 'small', 'b' => 'large', 'c' => 'short']],
9 => ["Which sentence is future?", ['a' => 'I go to the gym.', 'b' => 'I went to the gym.', 'c' => 'I will go.']],
10 => ["If I ___ rich...", ['a' => 'were', 'b' => 'was', 'c' => 'am']],
11 => ["He ____ every day.", ['a' => 'studies', 'b' => 'study', 'c' => 'studying']],
12 => ["They ____ dinner now.", ['a' => 'ate', 'b' => 'are eating', 'c' => 'eats']],
13 => ["We ____ to Canada last year.", ['a' => 'go', 'b' => 'gone', 'c' => 'went']],
14 => ["I have ____ this movie.", ['a' => 'seen', 'b' => 'see', 'c' => 'saw']],
15 => ["Opposite of 'cold'?", ['a' => 'hot', 'b' => 'warm', 'c' => 'cool']],
16 => ["He is ____ than his brother.", ['a' => 'tall', 'b' => 'taller', 'c' => 'more tall']],
17 => ["I ____ playing guitar.", ['a' => 'enjoy', 'b' => 'enjoys', 'c' => 'enjoyed']],
18 => ["We ____ at home yesterday.", ['a' => 'are', 'b' => 'were', 'c' => 'was']],
19 => ["He ____ already finished.", ['a' => 'have', 'b' => 'has', 'c' => 'had']],
20 => ["How ____ sugar do you want?", ['a' => 'much', 'b' => 'many', 'c' => 'some']],
21 => ["They ____ to travel soon.", ['a' => 'go', 'b' => 'are going', 'c' => 'goes']],
22 => ["She ____ TV every night.", ['a' => 'watches', 'b' => 'watch', 'c' => 'watched']],
23 => ["We ____ seen that film.", ['a' => 'has', 'b' => 'saw', 'c' => 'have']],
24 => ["Would you like ____ tea?", ['a' => 'any', 'b' => 'some', 'c' => 'many']],
25 => ["Can you ____ me please?", ['a' => 'hear', 'b' => 'listen', 'c' => 'help']]
];
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Teste de Nivelamento Interativo</title>
<style>
body {
margin: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f0f4f8;
display: flex;
justify-content: center;
align-items: flex-start;
min-height: 100vh;
padding: 20px;
}
.quiz-container {
background: white;
width: 100%;
max-width: 700px;
border-radius: 15px;
box-shadow: 0 15px 35px rgba(0,0,0,0.1);
position: relative;
padding: 30px 40px 50px;
box-sizing: border-box;
}
/* Progress Bar */
.progress-bar {
height: 14px;
background: #e2e8f0;
border-radius: 30px;
overflow: hidden;
margin-bottom: 25px;
}
.progress-bar-fill {
height: 100%;
width: 0;
background: linear-gradient(90deg, #2563EB, #3B82F6);
border-radius: 30px;
transition: width 0.4s ease;
}
/* Perguntas */
.question {
display: none;
flex-direction: column;
animation: fadeIn 0.5s ease;
}
.question.active {
display: flex;
}
.question-text {
font-weight: 700;
font-size: 1.3rem;
margin-bottom: 18px;
color: #1e293b;
}
label {
background: #f8fafc;
padding: 12px 18px;
border-radius: 12px;
margin: 6px 0;
cursor: pointer;
user-select: none;
color: #334155;
transition: background-color 0.2s, box-shadow 0.2s;
border: 2px solid transparent;
font-size: 1rem;
}
label:hover, label:focus-within {
background: #e0e7ff;
box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
}
input[type="radio"] {
margin-right: 12px;
accent-color: #2563eb;
cursor: pointer;
}
/* Navegação */
.btn-next {
margin-top: 30px;
background: #2563eb;
color: white;
border: none;
padding: 14px 36px;
font-size: 1.1rem;
font-weight: 700;
border-radius: 30px;
cursor: pointer;
box-shadow: 0 6px 18px rgba(37, 99, 235, 0.5);
transition: background-color 0.3s, box-shadow 0.3s;
align-self: flex-end;
user-select: none;
}
.btn-next:disabled {
background: #94a3b8;
cursor: not-allowed;
box-shadow: none;
}
.btn-next:hover:not(:disabled) {
background: #1e40af;
box-shadow: 0 8px 25px rgba(30, 64, 175, 0.7);
}
/* Resultado Popup */
.result-popup {
position: fixed;
top: 15px;
left: 50%;
transform: translateX(-50%);
background: #2563eb;
color: white;
padding: 22px 36px;
box-shadow: 0 8px 25px rgba(37, 99, 235, 0.7);
border-radius: 12px;
text-align: center;
font-weight: 700;
font-size: 1.25rem;
max-width: 350px;
z-index: 9999;
opacity: 0;
pointer-events: none;
transition: opacity 0.4s ease, top 0.4s ease;
}
.result-popup.show {
opacity: 1;
pointer-events: auto;
top: 30px;
}
.btn-dashboard {
margin-top: 14px;
background: white;
color: #2563eb;
border: none;
border-radius: 25px;
padding: 10px 28px;
font-weight: 700;
cursor: pointer;
box-shadow: 0 6px 15px rgba(59, 130, 246, 0.5);
transition: background-color 0.3s, color 0.3s;
}
.btn-dashboard:hover {
background: #e0e7ff;
}
/* Animação fadeIn */
@keyframes fadeIn {
0% {opacity: 0; transform: translateY(20px);}
100% {opacity:1; transform: translateY(0);}
}
@media(max-width: 480px) {
.quiz-container {
padding: 25px 20px 40px;
}
.btn-next {
width: 100%;
font-size: 1.15rem;
}
}
</style>
</head>
<body>
<div class="quiz-container" role="main" aria-live="polite">
<div class="progress-bar" aria-label="Progresso do teste">
<div class="progress-bar-fill" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"></div>
</div>
<form id="quizForm" novalidate>
<?php foreach($questions as $num => $q): ?>
<section class="question" id="question-<?= $num ?>" aria-labelledby="questionLabel-<?= $num ?>" tabindex="0">
<div class="question-text" id="questionLabel-<?= $num ?>"><?= $num ?>. <?= htmlspecialchars($q[0]) ?></div>
<?php foreach($q[1] as $key => $value): ?>
<label>
<input type="radio" name="answers[<?= $num ?>]" value="<?= $key ?>" required />
<?= htmlspecialchars($value) ?>
</label>
<?php endforeach; ?>
</section>
<?php endforeach; ?>
<button type="button" id="btnNext" class="btn-next" disabled>Próxima</button>
</form>
</div>
<div class="result-popup" role="alert" aria-live="assertive" aria-atomic="true" tabindex="0">
<div id="resultMessage"></div>
<button id="goDashboard" class="btn-dashboard" type="button">Ir para Dashboard</button>
</div>
<script>
(function(){
const totalQuestions = <?= count($questions) ?>;
let currentQuestion = 1;
const form = document.getElementById('quizForm');
const questions = form.querySelectorAll('.question');
const btnNext = document.getElementById('btnNext');
const progressFill = document.querySelector('.progress-bar-fill');
const popup = document.querySelector('.result-popup');
const resultMessage = document.getElementById('resultMessage');
const btnDashboard = document.getElementById('goDashboard');
// Mostra a pergunta de índice n
function showQuestion(n) {
questions.forEach(q => q.classList.remove('active'));
const current = document.getElementById('question-' + n);
current.classList.add('active');
current.focus();
updateProgress(n);
updateButtonState();
}
// Atualiza barra de progresso em %
function updateProgress(n) {
const percent = ((n - 1) / totalQuestions) * 100;
progressFill.style.width = percent + '%';
progressFill.setAttribute('aria-valuenow', Math.round(percent));
}
// Checa se tem radio marcado na pergunta atual pra habilitar botão
function updateButtonState() {
const current = document.getElementById('question-' + currentQuestion);
const checked = current.querySelector('input[type="radio"]:checked');
btnNext.disabled = !checked;
btnNext.textContent = currentQuestion === totalQuestions ? 'Enviar' : 'Próxima';
}
// Atualiza botão quando o usuário seleciona uma resposta
questions.forEach(q => {
q.addEventListener('change', e => {
if(e.target.matches('input[type="radio"]')) {
updateButtonState();
}
});
});
// Avançar ou enviar respostas
btnNext.addEventListener('click', () => {
if (currentQuestion < totalQuestions) {
currentQuestion++;
showQuestion(currentQuestion);
} else {
enviarRespostas();
}
});
// Envia respostas com fetch ajax para processar_respostas.php
function enviarRespostas() {
btnNext.disabled = true;
btnNext.textContent = 'Enviando...';
const formData = new FormData(form);
fetch('processar_respostas.php', {
method: 'POST',
body: formData,
credentials: 'same-origin',
headers: {'X-Requested-With': 'XMLHttpRequest'}
})
.then(res => res.text()) // pegar texto bruto primeiro
.then(text => {
try {
const data = JSON.parse(text);
if(data.success){
mostrarPopupResultado(data.score, data.level);
} else {
alert('Erro: ' + (data.error || 'Não foi possível processar as respostas.'));
btnNext.disabled = false;
btnNext.textContent = 'Enviar';
}
} catch(e) {
alert('Resposta inválida do servidor:\n' + text);
btnNext.disabled = false;
btnNext.textContent = 'Enviar';
}
})
.catch(err => {
alert('Erro de conexão: ' + err.message);
btnNext.disabled = false;
btnNext.textContent = 'Enviar';
});
}
// Exibe popup resultado no topo
function mostrarPopupResultado(score, level) {
resultMessage.innerHTML = `
Você acertou <strong>${score}</strong> de ${totalQuestions} perguntas.<br />
Seu nível estimado é: <strong>${level}</strong>.
`;
popup.classList.add('show');
popup.focus();
// Esconde quiz e barra de progresso
form.style.display = 'none';
document.querySelector('.progress-bar').style.display = 'none';
}
// Botão leva para dashboard
btnDashboard.addEventListener('click', () => {
window.location.href = 'index.php'; // ajustar para sua página dashboard
});
// Inicializa quiz
showQuestion(currentQuestion);
})();
</script>
</body>
</html>
2) processar_respostas.php (processa dados, responde JSON, usado no fetch)
<?php
session_start();
header('Content-Type: application/json; charset=utf-8');
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'Não autorizado']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['answers']) || !is_array($_POST['answers'])) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'Requisição inválida']);
exit;
}
require_once 'includes/db.php';
$correctAnswers = [
1 => 'b', 2 => 'a', 3 => 'c', 4 => 'a', 5 => 'b',
6 => 'c', 7 => 'a', 8 => 'b', 9 => 'c', 10 => 'a',
11 => 'a', 12 => 'b', 13 => 'c', 14 => 'a', 15 => 'a',
16 => 'b', 17 => 'a', 18 => 'b', 19 => 'b', 20 => 'a',
21 => 'b', 22 => 'a', 23 => 'c', 24 => 'b', 25 => 'c'
];
$answers = $_POST['answers'];
$userId = $_SESSION['user_id'];
$score = 0;
foreach ($correctAnswers as $question => $correct) {
if (isset($answers[$question]) && $answers[$question] === $correct) {
$score++;
}
}
if ($score <= 5) {
$level = 'A1';
} elseif ($score <= 10) {
$level = 'A2';
} elseif ($score <= 15) {
$level = 'B1';
} elseif ($score <= 20) {
$level = 'B2';
} elseif ($score <= 23) {
$level = 'C1';
} else {
$level = 'C2';
}
// Atualizar o nível no banco (assumindo $pdo conectado)
try {
$stmt = $pdo->prepare("UPDATE users SET level = :level, placement_done = 1 WHERE id = :id");
$stmt->execute([
':level' => $level,
':id' => $userId
]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'Erro ao atualizar banco']);
exit;
}
// Retornar resultado JSON
echo json_encode([
'success' => true,
'score' => $score,
'level' => $level
]);
exit;
?>
Considerações finais
- Ajuste
window.location.href = 'index.php' no JS para o caminho correto do seu dashboard.
- Garanta que o arquivo
includes/db.php esteja configurado corretamente e conecte com seu PDO $pdo.
- Teste os dois arquivos juntos.
- Atenção para sessões funcionando em AJAX (cookies liberados).
- Se usar controle de acesso externo, certifique-se de que não há redirecionamento HTML no
processar_respostas.php.
Se quiser posso ajudar a montar um arquivo de includes/db.php básico, ou fazer ajustes extras!
Com isso seu quiz vai ser moderno, progressivo, acessível e user-friendly com resposta em popup. 👍
Qualquer dúvida, só falar!