我使用Laravel 5.我在OrganisationsController我有一個方法的addItem如何用ajax Laravel進行驗證5.3
public function addItem(Request $request)
{
$rules = array(
'nom' => 'required',
);
// for Validator
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
return Response::json(array('errors' => $validator->getMessageBag()->toArray()));
else {
$section = new Section();
$section->nom = $request->nom;
$section->save();
return response()->json($section);
}
}
Ajax代碼
$("#add").click(function() {
$.ajax({
type: 'post',
url: '/addItem',
data: {
'_token': $('input[name=_token]').val(),
'nom': $('input[name=nom]').val()
},
success: function(data) {
if ((data.errors)) {
$('.error').removeClass('hidden');
$('.error').text(data.errors.title);
$('.error').text(data.errors.description);
} else {
$('.error').remove()
$('table').append("<tr class='section" + data.id + "'><td>" + data.id + "</td><td>" + data.nom + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-nom='" + data.nom + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-nom='" + data.nom + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>"); }
}
});
$('#noom').val('');
});
HTML代碼
<div class="form-group row add">
<div class="col-md-5">
<input type="text" class="form-control " id="noom" name="nom"
placeholder="New section here" required>
\t \t <p class="error text-center alert alert-danger hidden"></p>
</div>
<div class="col-md-2">
<button class="btn btn-warning" type="submit" id="add">
<span class="glyphicon glyphicon-plus"></span> Add new Section
</button>
</div>
</div>
我不知道爲什麼我的驗證無法正常工作。請爲此提供一個示例。我正在使用laravel 5.我搜索了很多網站。但我無法得到解決方案。
它仍然在同一個問題:( – meduprise
我發現** **溶液!!! 溶液是刪除的條件**如果( data.errors)** **感謝您的幫助** – meduprise