gpt4 book ai didi

php - Ajax 检索错误无法正常工作 Laravel

转载 作者:行者123 更新时间:2023-12-01 05:13:25 26 4
gpt4 key购买 nike

当用户填写使用 ajax 提交的表单时,我试图检索错误。我正在关注这个tutorial 。尽管我认为逻辑应该是正确的,但我没有得到预期的结果。这是我的 Blade View 代码:

@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

Controller 存储功能:

 /**
* 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()]);

}

问题是我根本没有收到消息,无论是成功还是错误。我不知道我哪里做错了。

附:我已经使用 Ajax 来提交此表单。我使用 XMLHttpRequest 对象做到了。问题是我不知道如何使用 422 状态来使用此 XHR 对象返回错误。我已经寻找过,但发现没有什么真正有用的。所以我改变了这个方法,在这里使用 ajax() jquery 函数,它似乎更常用。仍然没有收到消息。这是我第一次尝试使用 Ajax 来管理验证错误。非常欢迎您的帮助

最佳答案

您可以在 Controller 上使用它。

return response()->json(array('errors'=>$validator->getMessageBag()->toArray(),));

并在 javascript 中尝试使用这个

                    success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}

ajax代码

                   $.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
});

Controller

 public function store(Request $request)
{
$validator = \Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);


if ($validator->fails()) {
return response()->json(array('error'=>$validator->getMessageBag()->toArray(),));
}
$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();

return response()->json(array('success'=>'Added new records.',));
}

关于php - Ajax 检索错误无法正常工作 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56710915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com