Ajax检索错误不起作用Laravel

时间:2019-06-21 22:00:18

标签: php jquery ajax laravel validation

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

@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对象返回错误。我一直在寻找它,但没有发现真正有用的方法。因此,我将这种方法更改为在此处使用ajax()jquery函数,该函数似乎更常用。仍然没有收到消息。这是我第一次尝试使用Ajax管理验证错误。非常欢迎您的帮助

3 个答案:

答案 0 :(得分:0)

您可以使用Laravel Request进行验证。

php artisan make:request ThemeCreateRequest

控制器

use App\Http\Request\ThemeCreateRequest

 public function store(ThemeCreateRequest $request)
    {
        $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()]);

   }

App \ Http \ Request \ ThemeCreateRequest.php

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'intitule' => 'required|unique',
    ];
}

答案 1 :(得分:0)

您可以在控制器上使用它。

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);
                        }
                    }
                });

控制器

 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.',));
       }

答案 2 :(得分:0)

糟糕,这是我的错...我刚刚弄清楚了为什么它不起作用。我已将其放置在刀片视图中

@if($errors->any())
<ol style="color: red">
@foreach($errors->all() as $error)
<li>
  {{$error}}
</li>
@endforeach
</ol>
@endif

而不是JavaScript代码正在寻找以输出错误的<ul> </ul>标签。谢谢大家