I am building a quiz, I want to get all the questions + answers to them with a single call and I get them through an AJAX call so I can display them 1 by 1 with javascript
When I display the first question, the user selects an answer and clicks on submit, I want to run another ajax request to check whether or not the answer is true and return the appropriate thing
When the second ajax call starts it returns 500 (internal server error)
How do I fix this? Also, is there a better way to do what I am trying to do? The questions ara randomly selected from the db so refreshing the form runs that selection again and the randomness is gone, that's why I want to do it with ajax calls
Is there maybe another way I can get for example 10 questions from the db and pass them all at once to the view and then display 1 by 1 when question is answered?
I am looking for a solution on how to send the second call or maybe another idea on how I can write this better to achieve what I want
This is my form:
{!! Form::open(array('class'=>'question ajax challenge', 'id' => 'message')) !!}
{{--{!! Form::hidden('questionId', $question->id) !!}--}}
{!! csrf_field() !!}
{{--<h1 class="question-name">{{ $question->question }}?</h1>--}}
<h1 class="question-name"></h1>
<div class="form-group answers"></div>
{!! Form::submit('Send answer', ['class'=>'btn btn-send']) !!}
{!! Form::close() !!}
</div>
This is my JS:
$(document).ready(function () {
var totalQuestions;
var currentQuestion = 0;
var questions = new Array();
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/polls/get-questions',
data: {
questions: 'questions'
},
success: function(questions){
console.log(questions.questions);
// for(i=0;i<questions.questions.length;i++){
//
// questionBank[i]=questions.questions[i].question;
// questionBank[i]=questions.questions[i].answers;
// console.log(questionBank);
// }
for (var i in questions.questions) {
questions[i]=new Array;
questions[i][0] = questions.questions[i];
questions[i][1] = questions.questions[i].answers[0];
questions[i][2] = questions.questions[i].answers[1];
questions[i][3] = questions.questions[i].answers[2];
questions[i][4] = questions.questions[i].answers[3];
}
console.log(questions[0]);
//
totalQuestions=questions.length;
//
displayQuestion(questions[currentQuestion], csrf);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
function displayQuestion(question, csrf) {
var rnd=Math.random()*3;
rnd=Math.ceil(rnd);
var answer = new Array();
if(rnd==1){answer[1]=question[1];answer[2]=question[2];answer[3]=question[3];answer[4]=question[4];}
if(rnd==2){answer[2]=question[4];answer[3]=question[2];answer[4]=question[1];answer[1]=question[3];}
if(rnd==3){answer[4]=question[1];answer[3]=question[4];answer[1]=question[2];answer[2]=question[3];}
console.log(question[0]['id']);
$('.ajax').append('<input type="hidden" name="questionId" value="'+question[0]['id']+'" />');
$('.question-name').append(question[0].question);
for(var i=1;i<=4;i++)
{
$('.answers').append('' +
'<div class="radio">' +
' <label class="label-for-answer">' +
' <div class="input-radio col-md-12">' +
' <input id="'+answer[i]['id']+'" class="required answer-box" name="chosenAnswer" type="radio" value="'+answer[i]['id']+'">' +
' <label for="'+answer[i]['id']+'"><span class="number-to-letter"></span>'+answer[i]['name']+'</label>' +
' </div>' +
' </label>' +
'</div>');
}
$('form.ajax').on('submit', function(e){
var form = $(this);
$.ajax({
type: 'POST',
url: '/polls/message_send',
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').attr('value')
},
dataType:'json',
data: form.serialize(),
success: function (response) {
alert(response.correctSolution);
}
});
e.preventDefault();
});
$('.input-radio').click(function(){
//remove all pre-existing active classes
$('.main-yellow').removeClass('main-yellow');
//add the active class to the link we clicked
$(this).addClass('main-yellow');
});
}
And this is the Controller method that checks whether or not the question is true and returns json based on that:
public function proposeSolution(Request $request) {
$questionId = $request->get('questionId');
$question = Question::find($questionId);
$answers = $question->answers()->get()->toArray();
// Prepare array of proposed answers
$proposedSolution = [];
$proposedSolution[] = (int)$request->get('chosenAnswer');
// Prepare array of correct answers
$correctSolution = [];
foreach($answers as $answer) {
if ($answer['is_correct']) {
$correctSolution[] = $answer['id'];
}
}
$proposedSolutionResult = ($proposedSolution == $correctSolution);
// pass to response detailed results on proposed solution
$proposedSolutionWithDetailedResult = [];
foreach ($proposedSolution as $answerId) {
foreach ($answers as $answer) {
if ($answer['id'] == $answerId) {
$is_correct = $answer['is_correct'];
}
}
$proposedSolutionWithDetailedResult[$answerId] = $is_correct;
}
foreach($proposedSolution as $answerId) {
foreach ($answers as $answer) {
if ($answer['id'] == $answerId)
{
if($answer['is_correct'] == 1)
{
$quiz_result_score = session('quiz_result_score');
session(['quiz_result_score' => ++$quiz_result_score]);
}
}
}
}
return response()->json([
'correctSolution' => $correctSolution,
'proposedSolutionWithDetailedResult' => $proposedSolutionWithDetailedResult,
'proposedSolutionResult'=> $proposedSolutionResult
]);