【Laravel】Ajaxで取得したデータをinputタグにvalueとして渡す方法

【Laravel】Ajaxで取得したデータをinputタグにvalueとして渡す方法

こんにちは!

今回はLaravelで非同期通信処理ajaxを用いて取得したデータをinputタグにvalueとして渡す方法を解説していきます。

Laravelにおいて、更新処理をする際に該当となるレコードの情報を取得してきてモーダルで表示させるという処理を業務で行ったので、アウトプットとしてここに記述していきたいと思います。

ajax処理の基本的な書き方

まずはajaxの基本的な書き方から。

$(function(){
  $.ajax({
    type: "get", //HTTP通信の種類
    url:'/home', //通信したいURL
    dataType: 'json'
  })
  //通信が成功したとき
  .done((res)=>{
    console.log(res.message)
  })
  //通信が失敗したとき
  .fail((error)=>{
    console.log(error.statusText)
  })
});

こんな感じ。

更新処理

目的としては、変更ボタンを押すと変更画面モーダルが表示され、該当レコードのデータが変更画面に最初から入力されている状態を実現したい。

通常は画面を別のbladeファイルで分けて変更ボタンを押した際に該当レコードのidがリクエストとしてサーバーに送られ、ControllerやModelでそのidに紐づくデータを取り出してきて、変更画面に表示させるのが一般的だと思います。

ただし、今回は変更画面をモーダルで表示させたいので、リクエストされる該当レコードのidをブラウザ上で処理し、サーバーにはデータを送らず、Controllerにデータをそのまま返させます。そのデータをモーダル上で表示させるという処理を書いていきたいと思います。

<table class="table table-striped table-hover">
    <thead>
        <tr>
            <th>出荷数</th>
            <th>処理</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>{{ $order_sipment->sipment_quantity }}</td>
            <td>
                <button type="button" 
                        id="order_sipment_id"
                        class="btn btn-success" 
                        data-toggle="modal" 
                        data-target="#updateModal" 
                        data-quantity="{{ $order_sipment->sipment_quantity }}">
                    変更
                </button>
            </td>
        </tr>
    </tbody>
</table>

<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-fluid" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateModalLabel">出荷数の変更</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form action="{{ route('order_sipments.response') }}" method="post">
                    @csrf
                    <div class="row">
                        <div class="col-2">出荷数</div>
                        <div class="col-10">
                            <input type="number" class="form-control" id="order_sipment_quantity" name="sipment_quantity">
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
    .modal-dialog-fluid {
        max-width: inherit;
        width: 98%;
        margin-left: 15px;
    }
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<script>
$(function () {
    // 変更ボタンがクリックされた時の処理
    $('#order_sipment_id').on('click', function () {
        // CSRFトークンの設定(LaravelのPOST送信に必須)
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // ボタンのdata-quantity属性から値を取得
        let orderSipmentQuantity = $(this).data('quantity');

        // Ajax通信の実行
        $.ajax({
            type: "post",
            url: "/order_sipments/response",
            dataType: "json",
            data: {
                'quantity': orderSipmentQuantity
            }
        })
        .done(function(res) {
            console.log(res);
            // サーバーから返ってきた値をモーダルの入力欄にセット
            $('#order_sipment_quantity').val(res['quantity']);
        })
        .fail(function(error) {
            console.log("エラーが発生しました");
            console.log(error.statusText);
        });
    });
});
</script>
# Route
Route::post('/order_sipments/response', [App\Http\Controllers\OrderSipmentController::class, 'response'])
	->name('order_sipments.response')
	->middleware('auth');
# Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class OrderSipmentController extends Controller 
{
    // リクエストされた値をそのまま返すだけ!
    public function response(Request $request)
    {
        return $request; 
    } 
}

肝としてはViewファイルのAjax処理の書き方ですね。

変更ボタンを押した際にAjaxで非同期にモーダル上のフォームのinputタグにvalueとして$order_sipment->sipment_quantityという値を与えます。

$order_sipment->sipment_quantityについては記述を省略しておりますが、DBの中のテーブルから持ってきた出荷数のデータの値になります。

Viewファイルで書いたAjax処理を行なったときにajaxの中で定義されているdataがControllerに行きますが、サーバーでは処理せず、Controllerでそのままdataを返しています。

そして返ってきたdataはajax処理の.then()の処理に移行し、この時にモーダル上のinputタグにvalueとして$order_sipment->sipment_quantityの値が入ります。

このような処理を行うことで、モーダル表示した際に該当レコードの出荷数の値がフォームに入力された状態で表示されるというわけです。

それでは、今回はこんなところで!