如果有验证错误显示视图中的错误(使用ajax post请求)

时间:2018-04-20 15:41:50

标签: jquery laravel

我有一个多步骤表格。在步骤1中,用户需要输入信息,如姓名,姓氏等。当用户点击“转到步骤2”时,向控制器方法storeUserInfo发送ajax post请求以验证用户引入的信息。 / p>

您知道吗,如果有验证错误如何在视图中显示错误(在step1表单上方)?

我有一个带有以下内容的errors.blade.php文件。在我不使用ajax的表单中,为了显示验证错误,我只使用“@include('includes.errors')”。但是ajax并没有像那样工作。 Errors.blade.php:

@if ($errors->any())
    <div class="alert alert-danger mt-3">
        <ul>
            @foreach ($errors->all() as $error)
                <li class="text-danger">{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

PaymentController方法:我有最大1的buyer_name只是为了测试验证

public function storeUserInfo(Request $request, $id, $slug = null){
        //dd($request);
        $request->validate([
            'buyer_name' => 'required|max:1|string',
            'buyer_surname' => 'required|max:255|string',
            'buyer_email' => 'required|max:255|email',
            'name_invoice' => 'required|max:255|string',
            'country_invoice' => 'required|max:100|string',
        ]);
        return redirect(route('products.presentPaymentMethods',['id' => $id, 'slug' => $slug]));

    }

发布请求的路由:

Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [
    'uses' => 'PaymentController@storeUserInfo',
    'as'   =>'products.storeUserInfo'
]);

step1 html:

<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
    <h6>User Info</h6>
    <form method="post" id="step1form" action="">
         {{csrf_field()}}
        <div class="form-group font-size-sm">
            <label for="name" class="text-gray">Name</label>
            <input type="text" required class="form-control"  value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
        </div>
        <!-- other form fields -->
        <input type="submit" id="goToStep2" href="#step2"
                class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
    </form>
</div>

jQuery的:

var page_form_id = "step1form";

$('#goToStep2').on('click', function () {
    var custom_form = $("#" + page_form_id);
    var custom_params = custom_form.serializeArray();
    var custom_formData = new FormData();

    $(custom_params).each(function (custom_index, custom_element) {
        custom_formData.append(custom_element.name, custom_element.value);
    });

    $.ajax({
        method: "POST",
        url: '{{ route('products.storeUserInfo',null) }}',
        contentType: false,
        processData: false,
        data: custom_formData,

        success: function (data, textStatus, jqXHR) {
            setTimeout(function () {
                window.location.reload();
            }, 3000);
        },
        error: function (data) {
            var errors = data.responseJSON;
            $.each(errors['message'], function (index, value) {

            });
        }
    });

    });
});

0 个答案:

没有答案