Я пытаюсь найти ошибки, когда пользователь заполняет форму, отправленную с использованием ajax. Я следую этому учебнику . Я не получаю ожидаемого результата, несмотря на логику, которую считаю правильной
Вот мой код вида лезвия:
@extends('layouts.layout')
@section('title','Soumettre thématique')
@section('content')
<body>
<div class="container_fluid">
<div class="row">
<div class="alert alert-danger print-error-msg" style="display: none;">
@if($errors->any())
<ol style="color: red">
@foreach($errors->all() as $error)
<li>
{{$error}}
</li>
@endforeach
</ol>
@endif
</div>
</div>
</div>
<form method="POST" action=" {{route('themes.store')}} ">
@csrf
<!-- Intitulé du thème -->
<input type="text" name="intitule" id="intitule" placeholder="Intitulé du thème" required><br>
<!-- Catégorie -->
<select name="categorie" required>
<option value="">-- Catégorie --</option>
<option value="web">Développement web</option>
<option value="appMobile">Programmation application mobile</option>
<option value="secure">Sécurisation</option>
<option value="other">Autre</option>
</select> <br>
<!-- Filière désirée -->
<input type="checkbox" name="filiere[]" id="GL" value="GL" required>
<label for="GL">Génie Logiciel</label><br>
<input type="checkbox" name="filiere[]" id="SI" value="SI" required>
<label for="SI">Sécurité Informatique</label><br>
<input type="checkbox" name="filiere[]" id="IM" value="IM" required>
<label for="IM">Internet et Multimédia</label><br>
<input type="checkbox" name="filiere[]" id="SIRI" value="SIRI" required>
<label for="SIRI">Systèmes d'Information et Réseaux Informatiques</label><br>
<!-- Descriptif -->
<textarea name="description" id="description" placeholder="Description de la thématique" required>{{old('description')}} </textarea><br>
<input type="submit" name="submit" id="submit" value="Ajouter">
<span id="error-message" class="text-danger"></span>
<span id="success-message" class="text-success"></span>
</form>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function (){
var itsChecked = null;
$('input[type=checkbox]').on('click', function(){
if($('input[type=checkbox]:checked').length > 0){ //S'il y a au moins 1 ([...].length > 0) ckecked
// alert('At least one is checked');
$('#GL').removeAttr("required");
$('#SI').removeAttr("required");
$('#IM').removeAttr("required");
$('#SIRI').removeAttr("required");
}
else if(!$('input[type=checkbox]:checked').length > 0){ //S'il n'y a aucun checked (!(at least 1)>0)
// alert('None is checked');
$('#GL').attr('required','');
$('#SI').attr('required','');
$('#IM').attr('required','');
$('#SIRI').attr('required','');
}
});
$('#submit').on('click',function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var intitule = $("input[name='intitule']").val();
var categorie = $("select[name='categorie']").val();
var filiereChecked = [];
$.each($("input[type='checkbox']:checked"), function(){
filiereChecked.push($(this).val());
});
var filiere = filiereChecked.join(", ");
var filiere = filiere.toString();
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if($.isEmptyObject(data.error)){
alert(data.success);
}
else{
// console.log(data.error);
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
</body>
@endsection
Функция хранилища контроллера:
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
Проблема в том, что я вообще не получаю сообщения, может быть, это успех или ошибка. Я не знаю, где я делаю не так там.
P.S:
Я уже использовал Ajax для отправки этой формы. Я сделал это с помощью объекта XMLHttpRequest. Проблема была в том, что я не знаю, как использовать состояние 422 для возврата ошибок с использованием этого объекта XHR. Я искал это, но не нашел ничего действительно полезного. Поэтому я изменил этот метод, чтобы использовать здесь функцию jjery ajax (), которая кажется более используемой. Все еще не получаю сообщения. Я впервые пытаюсь управлять ошибками проверки с помощью Ajax. Ваша помощь будет приветствоваться