LoginSignup
0
0

More than 3 years have passed since last update.

【PHP】Ajax

Last updated at Posted at 2021-01-17
blade.php
<!-- ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    $('#answer-btn').on('click', function () {
      $question_id = {{ $question->id }};
      $answer_choice = {{ $question->answer_choice }};
      $answered_choice = Number($('input[name="answer"]:checked').val());
      console.log($answered_choice);
      console.log($answer_choice);
      console.log($question_id);
       $.ajax({
        type: "POST",
        url: "/question/choice",
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        data: { 'answered_choice': $answered_choice, 'question_id': $question_id },
      });
    })
</script>
<!-- ajax -->
QuestionController.php
  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function choice(Request $request)
  {
      $answered_choice = $request->answered_choice;
      $question_id = $request->question_id;
      $question = Question::find($question_id);
      if($answered_choice == $question->answer_choice){
        $question->update(["status_num" => 2]);
      } else {
        $question->update(["status_num" => 3]);
      }
  }
web.php
use App\Http\Controllers\QuestionController;
Route::resource('/question',  QuestionController::class)->middleware('auth');
Route::post('/question/choice',  [QuestionController::class, 'choice'])->middleware('auth');
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0