使用 Laravel 和 Ajax 更新数据库 - 无法访问控制器中的更新方法的问题

Updating database with Laravel and Ajax - issue with the update method in the controller not being reached

提问人:Conlaodh Quinn 提问时间:2/2/2022 最后编辑:Conlaodh Quinn 更新时间:2/2/2022 访问量:200

问:

我正在尝试使用 Laravel 和 Ajax 更新表单。但是,当我单击“提交”时,页面不会重定向到我指定的路由(在控制器的更新方法中),而是刷新页面,并且不会对数据库表进行任何更改。为了清楚起见,我将包含我的代码片段。我觉得这个问题与无法到达控制器有关,但我不确定为什么会这样。关于这个问题的任何帮助或建议将不胜感激!

编辑表单

<div class="flex-1 px-10">
<form method="POST" class="is-readonly" >
      <input type="hidden" name="_method" value="PUT">
                @csrf

        <div class="row">
            @if ($errors->any()) <span>{{ $errors }}</span> @endif
         </div>
<div class="w-full md:w-1/2 flex flex-col">
                                <div class="md:flex md:items-center mb-6">
                                    <label class="font-bold text-neutral-darker leading-none md:pr-2 sm:pr-4"
                                        for="agreement_type_id">Agreement Type:</label>
                                    <select
                                        class="leading-none w-64 text-gray-900 py-2 px-4 focus:outline-none focus:border-blue-700 mt-4 bg-gray-100 border rounded border-gray-200 is-disabled @error('agreement_type_id') is-invalid @enderror"
                                        id="grid-state"
                                        value="{{ old('agreement_type_id') ?? $grantorAgreement->agreement_type_id }}" name= "agreement_type_id">
                                        <option value="0" disabled selected>Please Select</option>
                                        @foreach ($agreementTypes as $agreementType)
                                            @if ($grantorAgreement->agreement_type_id == $agreementType->id)
                                                <option value="{{ $agreementType->id }}" selected>
                                                    {{ $agreementType->agreement_type_details }}</option>
                                            @else
                                                <option value="{{ $agreementType->id }}" >
                                                    {{ $agreementType->agreement_type_details }}</option>
                                                    @endif
                                            @endforeach

                                    </select>
                                </div>
                            </div>
                  </div>
     <div class="text-right mb-2 mt-3.5">
              <button type = "button" name = "update" id = "update_grantor_agreement" class="grantors-btn rounded-full font-bold bg-indigo-500 px-4 py-2 text-white">Save Grantor Agreement</button>
            </div>
</form>

请注意,此表单中还有许多其他部分因篇幅原因被省略。

Ajax 调用

 $(document).ready(function(){
            alert('test');

    $(document).on("click", "#update_grantor_agreement", function() {
        var url = "{{ route('grantors_agreements.update', [$grantor_id, 2) }}";
        // var grantor_name: $('#grantor_name').val();
        var gl_allocation_code = $('#gl_allocation_code').val();
        var agreement_type_id = $('#agreement_type_id').val()
        var agreement_sub_type_id = $('#agreement_sub_type_id').val();
        var vat_code_id = $('#vat_code_id').val();
        var payment_type_id = $('#payment_type_id').val();
        var wayleave_officer_id = $('#wayleave_officer_id').val();
        var payment_date = $('#payment_date').val();
        var memo = $('#memo').val();
        var token = $('meta[name="csrf-token"]').attr('content');
        $.ajax({
            url: "{{url, route('grantors_agreements.update' + [$grantor_id, $grantorAgreement->id])}}",
            type: "POST",
            cache: false,
      datatype: 'JSON',
            data:{
        "_method": 'POST',
      "_token":token,
      // "grantor_name":grantor_name,
      "gl_allocation_code": gl_allocation_code,
        "agreement_type_id":agreement_type_id,
        "agreement_sub_type_id":agreement_sub_type_id,
        "vat_code_id":vat_code_id,
        "payment_type_id":payment_type_id,
         "wayleave_officer_id":wayleave_officer_id,
        "payment_date":payment_date,
        "memo":memo
            },
     
    });
    });
});

控制器中的更新方法

public function update(Request $request, $grantor_id, $id)
    {
        $grantorAgreement = GrantorsAgreement::findOrFail($id);
        $grantor = Grantor::find($id);

        $grantorAgreement-> agreement_type_id = $request->input('agreement_type_id');
        $grantorAgreement-> agreement_sub_type_id = $request->input('agreement_sub_type_id');
        $grantorAgreement-> vat_code_id = $request->input('vat_code_id');
        $grantorAgreement-> payment_type_id = $request->input('payment_type_id');
        $grantorAgreement-> wayleave_officer_id = $request->input('wayleave_officer_id');
        $grantorAgreement-> payment_date = $request->input('payment_date');


      $grantorAgreement->save();

路由文件

Route::get('grantors/{grantor_id}/grantors_agreements/{id}/edit', [App\Http\Controllers\GrantorAgreementController::class, 'edit'])->name('grantors_agreements.edit') ;
Route::post('grantors/{grantor_id}/grantors_agreements/{id}/edit', [App\Http\Controllers\GrantorAgreementController::class, 'edit'])->name('grantors_agreements.edit') ;
Route::post('grantors/{grantor_id}/grantors_agreements/{id}/update', [App\Http\Controllers\GrantorAgreementController::class, 'update'])->name('grantors_agreements.update');
JavaScript PHP Ajax Laravel 表单

评论

0赞 Simon K 2/2/2022
向 添加属性以防止初始表单提交(重新加载)。在调试时,您可能还希望在 ajax success 回调中禁用。最后,我认为不是一个有效的jQuery ajax选项吗?也许你的意思是?type="button"buttonwindow.reloaduploadUrlurl
0赞 Conlaodh Quinn 2/2/2022
感谢您的回复,我已经实施了您的建议,现在在控制台日志中收到错误“POST 'myurl'/grantors/2/grantors_agreements/2/%7B%7Burl,%20route('grantors_agreements.update'%20+%20[$grantor_id,%20$grantorAgreement-%3Eid])%7D%7D 404 (Not Found) - 它似乎没有将我的 url 作为路由,你知道为什么会这样吗?
0赞 Arijeet Bose 2/2/2022
您能否用您所做的修改来更新问题。
0赞 Conlaodh Quinn 2/2/2022
@ArijeetBose我现在更新了,谢谢
0赞 Simon K 2/2/2022
将你的设置为$.ajax({url:"{{route('grantors_agreements.update', [$grantor_id, $grantorAgreement->id])}}"

答: 暂无答案