Laravel adding error messages to ajax post

2019-08-10 21:04发布

问题:

I am trying to make a form to submit via ajax in laravel 5 and it works to a certain point.

This is my ajax/jQuery:

$('#RegisterSubmit').click(function(e){
        e.preventDefault();
        var form = $('#RegisterForm');
            $.ajax({
                type: 'POST',
                url: '/register_process',
                data: form.serialize(),
                dataType: 'json',
                timeout: 9000,

            });
            $('#RegisterForm')[0].reset();

    });

Everything works fine, the user can register and information is sent to database but when the user makes an error I want there to be a message saying that.ex: 'username field is empty'.

I managed to do that by using html like this:

<div class="form-group">
        <label class = "col" for = "username" >username:</label>
     <div class = "col">
        <input id = "username" class=" input {{ $errors->has('username') ? 'has-error' : '' }}" type = "username" name = "username" value="{{ Input::old('username') }}"></input><br>
        {!! $errors->first('username' , '<span style = "color:red">:message</span>') !!}
     </div>
    </div>

But now i can't use this anymore as I am sending data with ajax, what can I do to fix this ?

These is how I show messages:

public function StoreRegister()
{
    $messages = [
        'unique' => 'Acest :attribute deja exista',
        'min' => 'Câmpul :attribute trebuie sa conţina cel puţin :min caractere',
        'required' => 'Campul :attribute trebuie completat',
        'email' => 'Campul :attribute trebuie sa fie valid'
    ];

    $validator = Validator::make(Input::all(),Register::$rules,$messages);
    if($validator->fails())
    {
        return Redirect::back()->withInput()->withErrors($validator);
    }

    Register::saveFormData(Input::except(array('_token')));
    return Redirect::to('/');
}

回答1:

$.ajax({
                    type: 'POST',
                    url: '/register_process',
                    data: form.serialize(),
                    dataType: 'json',
                    timeout: 9000,
                    error: function(data){
                        if( data.status === 422 ) {
                          var errors = data.responseJSON;
                          errorHtml='<div class="errors"><ul>';
                          $.each( errors, function( key, value ) {
                               errorHtml += '<li>' + value[0] + '</li>';
                         });
                          errorHtml += '</ul></div>';
                          $( '#formerrors' ).html( errorHtml );

                    }
                 }
         });

When using validate during ajax ,laravel generates json reponse containing each error messages and status of that response is 422.Do not forget to add a div for displaying errors.

<div id="formerrors"></div>