V
V
Vlad Avtomat2017-08-31 08:58:26
Laravel
Vlad Avtomat, 2017-08-31 08:58:26

How to display validation errors in a modal window on an AJAX request?

For example, I validate some fields:

$this->validate($request,
            [
                'name'=>'required',
                'file'=>'required',
                'transport_position' => 'numeric|between:1,99'
            ]);

In the modal window where the form is located, I insert the following example
from the documentation:
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

But nothing comes when the validation fails.
What am I doing wrong?
How to properly display JSON response 422?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Lysenko, 2017-08-31
@VladSavelev

how I did it, perhaps bydlokod

<form enctype="multipart/form-data" class="gl_form">
<input type="text" name="name">
<input type="text" name="name2">
<input type="text" name="name3">
<div id="order" class="btn btn-success form-control">Заказать</div>
</form>

$('#order').on('click', function(){
        var msg   = $('.gl_form').serialize();
        $.ajax({
            type: 'post',
            url: '{{url()->current()}}',
            headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
            data: msg,
            dataType: 'json',
            success: function(data){
                 if(data.success == 'yes'){
                    $('.yes').html('<h3>Спасибо за ваш заказа. Мы скоро с вами свяжемся</h3>');
                 }
                $.each(data, function(key, val) {
                    $.each(val, function(keyy, vall) {
                        $('.zakaz').prepend(vall);
                    });
                });

                 
            }
    });
    });

In the controller method at the
top, paste
use Illuminate\Http\Request;
use Validator;

then write your own method
public function Order(Request $request){

$messages = [
    'name.required' => 'Текст ошибки',
    'file.required' => 'Текст ошибки',
    'transport_position.numeric' => 'Текст ошибки',
    ];
$validator = Validator::make($request->all(), [
    'name'=>'required',
    'file'=>'required',
    'transport_position' => 'numeric|between:1,99'
    ],$messages);


//Если ошибки возвращаем респонс с ними
if ($validator->fails()) {
    return Response()->json(array('errors' => $validator->getMessageBag()->toArray()));
    }

//Если нет ошибок возвращаем респонс, что все окей
    return Response()->json(array('success' => 'yes'));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question