dsa99349 2019-06-21 22:00
浏览 80

Ajax检索错误不起作用Laravel

I'm trying to retrieve errors when a user fills a form submitted using ajax. I'm following this tutorial. I'm not getting the result expected despite the logic I think should be right. Here is my blade view code :

@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

The controller store function :

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

   }

The problem is I'm not getting a message at all, either success or error may it be. I don't know where I'm doing wrong there.

P.S: I've already used Ajax to submit this form. I did it using XMLHttpRequest object. The problem was I do not know how to use the 422 status to return errors using this XHR object. I've looked for it but found nothing really helpful.. So I changed this method to use here the ajax() jquery function which seems to be more used. Still not getting the messages.. It's the first time I try to manage the validation errors using Ajax. Your help would be very welcome

  • 写回答

3条回答 默认 最新

  • dougengqiu8031 2019-06-21 23:13
    关注

    You can use Laravel Request for your validation.

    php artisan make:request ThemeCreateRequest
    

    Controller

    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',
        ];
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记