我尝试使用jQuery anad AJAX创建一个多步骤表单。
在步骤1中,用户需要插入个人信息:姓名,姓氏等。当用户点击"转到步骤2"时,我向控制器方法{{1发送一个AJAX发布请求验证用户的信息。
我的问题是,如果出现验证错误,如何使用AJAX错误函数?
PaymentController storeUserInfo()
方法:
storeUserInfo()
//步骤1和步骤2 html
public function storeRegistrationInfo(Request $request, $id, $slug = null){
//dd($request);
$request->validate([
'name' => 'required|max:255|string',
'surname' => 'required|max:255|string',
...
]);
}
AJAX代码:
<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 name="name" 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>
<div class="tab-pane fade clearfix tabs hide" id="step2" role="tabpanel" aria-labelledby="profile-tab">
<form method="post">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="paymentmethod1" value="option1" checked>
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="credit_card" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Stripe</span>
</label>
</div>
</div>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<button type="button" data-nexttab="#step3" href="#step3"
class="btn btn-primary btn ml-2 next-step">
Go to step 3
</button>
</div>
</form>
</div>
// jquery在步骤之间导航:
var page_form_id = "step1form";
$('#goToStep2').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storeUserInfo',$id) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
}, 3000);
},
error: function (data) {
}
});
});
});
我有一个$(".next-step").click(function(e) {
var $active = $('.nav-pills li a.active');
nextTab($active);
});
$(".prev-step").click(function(e) {
var $active = $('.nav-pills li a.active');
prevTab($active);
});
function nextTab(elem) {
elem.parent().next().removeClass('disabled').find('a.nav-link').click();
}
function prevTab(elem) {
elem.parent().prev().find('a.nav-link').click();
}
文件,其中包含以下内容。在我不使用AJAX的表单中,我只使用errors.blade.php
来显示错误,但我不知道AJAX请求是否也可以使用它。
@include('includes.errors')
:
Errors.blade.php
答案 0 :(得分:0)