【问题标题】:Ajax retrieving errors not working LaravelAjax 检索错误不起作用 Laravel
【发布时间】:2019-11-04 17:54:34
【问题描述】:

当用户填写使用 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()]);

   }

问题是我根本没有收到消息,可能是成功也可能是错误。我不知道我在哪里做错了。

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

【问题讨论】:

    标签: php jquery ajax laravel validation


    【解决方案1】:

    您可以使用 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',
        ];
    }
    

    【讨论】:

    • 感谢您的回答。不应该是public function store(ThemeCreateRequest $request)吗?..我刚试了,还是没有回消息
    【解决方案2】:

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

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

    【讨论】:

    • 尝试了您的解决方案,但我仍然没有收到任何消息。我应该告诉服务器应该返回的内容类型吗?我说的是这行代码header("Content-Type: text/json");。我写了它,但不知道这是否是问题,因为我仍然不明白为什么它不起作用..
    • 您确定您的点击事件有效吗?我放的返回已经是一个对象,而 ajax 数据需要是一个 json/对象。也许您遇到其他错误?抱歉,我不知道header("Content-Type: text/json"); 有什么用,但我没有使用它,我收到一条错误消息和成功消息。
    • 是的,你是对的,没有它,它仍然有效。我已经解决了我的问题,在我看来这是一个错误。谢谢
    【解决方案3】:

    哎呀,这是我的错...我刚刚弄清楚为什么它不起作用。我把它放在我的刀片视图中

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

    而不是 JavaScript 代码正在寻找输出错误的 &lt;ul&gt; &lt;/ul&gt; 标记。谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 2015-04-17
      • 2015-09-08
      相关资源
      最近更新 更多