使用AJAX验证laravel模态窗体时出错

时间:2017-08-19 09:31:46

标签: php jquery ajax twitter-bootstrap laravel-5

我正在尝试使用ajax验证模式表单。我希望错误显示在模态而不是模态关闭。但这不起作用

我正在使用此repo- https://github.com/RyanSMurphy/Laravel-Bootstrap-Modal-Form

这是我的观点

<div class="modal fade" id="{{$item->id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
   <div class="modal-content">
     <form action = "{{url('requests/rfq/send')}}" method="post" class="bootstrap-modal-form">  
        <div class="modal-body">
            <input type="text" name="name">
        </div>
        <div class="modal-footer">
          <a class="btn btn-default btn-ok" data-dismiss="modal">Cancel</a>
         <input type="submit" value="submit"  class="btn btn-danger">
       </div>
  </form>
 </div>

 @section('script')
       <script type="text/javascript">
         $(document).ready(function() {
          // Prepare reset.

        function resetModalFormErrors() {
           $('.form-group').removeClass('has-error');
             $('.form-group').find('.help-block').remove();
        }
    // Intercept submit.
     $('form.bootstrap-modal-form').on('submit', function(event) {
          event.preventDefault();
          // Set vars.
          var form   = $(this),
          url    = form.attr('action'),
          submit = form.find('[type=submit]');

          // Check for file inputs.
         if (form.find('[type=file]').length) {
          // If found, prepare submission via FormData object.
             var input       = form.serializeArray(),
             data        = new FormData(),
             contentType = false;

           // Append input to FormData object.
            $.each(input, function(index, input) {

           data.append(input.name, input.value);
           });
          // Append files to FormData object.
                                                            $.each(form.find('[type=file]'), function(index, input) {
                                                                if (input.files.length == 1) {
                                                                    data.append(input.name, input.files[0]);
                                                                } else if (input.files.length > 1) {
                                                                    data.append(input.name, input.files);
                                                                }
                                                            });
                                                        }

                                                        // If no file input found, do not use FormData object (better browser compatibility).
                                                        else {
                                                            var data        = form.serialize(),
                                                                contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
                                                        }

                                                        // Please wait.
                                                        if (submit.is('button')) {
                                                            var submitOriginal = submit.html();
                                                            submit.html('Please wait...');
                                                        } else if (submit.is('input')) {
                                                            var submitOriginal = submit.val();
                                                            submit.val('Please wait...');
                                                        }

                                                        // Request.
                                                        $.ajax({
                                                            type: "POST",
                                                            url: url,
                                                            data: data,
                                                            dataType: 'json',
                                                            cache: false,
                                                            contentType: contentType,
                                                            processData: false

                                                        // Response.
                                                        }).always(function(response, status) {

                                                            // Reset errors.
                                                            resetModalFormErrors();

                                                            // Check for errors.
                                                            if (response.status == 422) {
                                                                var errors = $.parseJSON(response.responseText);

                                                                // Iterate through errors object.
                                                                $.each(errors, function(field, message) {
                                                                    console.error(field+': '+message);
                                                                    //handle arrays
                                                                    if(field.indexOf('.') != -1) {
                                                                        field = field.replace('.', '[');
                                                                        //handle multi dimensional array
                                                                        for (i = 1; i <= (field.match(/./g) || []).length; i++) {
                                                                            field = field.replace('.', '][');
                                                                        }
                                                                        field = field + "]";
                                                                    }
                                                                    var formGroup = $('[name='+field+']', form).closest('.form-group');
                                                                    formGroup.addClass('has-error').append('<p class="help-block">'+message+'</p>');
                                                                });

                                                                // Reset submit.
                                                                if (submit.is('button')) {
                                                                    submit.html(submitOriginal);
                                                                } else if (submit.is('input')) {
                                                                    submit.val(submitOriginal);
                                                                }

                                                            // If successful, reload.
                                                            } else {
                                                                location.reload();
                                                            }
                                                        });
                                                    });

                                                    // Reset errors when opening modal.
                                                    $('.bootstrap-modal-form-open').click(function() {
                                                        resetModalFormErrors();
                                                    });
                                                });  
                                        </script>
                                        @endsection

这是我的控制器

 public function send_rfq(Request $request){
        $validator = Validator::make($request->all(), [
            'name' =>'required'
        ]);
        if($validator->fails()){
            return back()
                ->withErrors($validator)
                ->withInput();
        }
    }

1 个答案:

答案 0 :(得分:-1)

您需要在表单中发送 @csrf