Второй Ajax Call возвращает 500 Внутренняя ошибка сервера - PullRequest
0 голосов
/ 23 января 2019

Я строю тест, я хочу получить все вопросы + ответы на них одним вызовом, и я получаю их с помощью вызова AJAX, чтобы я мог отображать их 1 на 1 с помощью JavaScript

Когда яотобразить первый вопрос, пользователь выбирает ответ и нажимает кнопку «Отправить». Я хочу выполнить еще один запрос ajax, чтобы проверить, верен ли ответ, и вернуть соответствующую вещь

Когда начинается второй вызов ajax, он возвращает500 (внутренняя ошибка сервера)

Как это исправить?Кроме того, есть ли лучший способ сделать то, что я пытаюсь сделать?Вопросы случайным образом выбираются из базы данных, поэтому при обновлении формы повторяется выбор, и случайность исчезает, поэтому я хочу сделать это с помощью вызовов ajax

Возможно, есть другой способ получить, например, 10 вопросовиз БД и передать их все сразу в представление, а затем отобразить 1 на 1, когда ответ на вопрос?

Я ищу решение о том, как отправить второй вызов, или, может быть, другую идею о том, как мне лучше написать это, чтобы достичь того, чего я хочу

Это моя форма:

 {!! 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>

Это мой 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');
    });

}

И это метод Controller, который проверяет, является ли вопрос верным и возвращает json, основываясь на этом:

    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
    ]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...