mercredi 29 mars 2017

Can't catch laravel validation with ajax

I'm trying to submit a form with ajax in Laravel 5.4.

The problem is, I can't catch the errors when the form does not validate.

In my view:

<?php
    $encrypter = app('Illuminate\Encryption\Encrypter');
    $encrypted_token = $encrypter->encrypt(csrf_token());
?>
<input id="token" type="hidden" value="">

My ajax code:

var $_token = $('#token').val();

 $.ajax({
    type: "POST",
    headers: { 'X-XSRF-TOKEN' : $_token },
    url: '',
    data:$("#checkoutForm").serialize(),
    dataType: 'json',
    success: function(data) {
      alert('success');
    },
    error: function( data ) {
      alert('error');

      /* if( data.code === 401 ) //redirect if not authenticated user.
            $( location ).prop( 'pathname', 'auth/login' );
              if( data.code === 422 ) {
              //process validation errors here.
                var errors = data.errors; //this will get the errors response data.
             //show them somewhere in the markup
             //e.g
             errorsHtml = '<div class="alert alert-danger"><ul>';

             $.each( errors , function( key, value ) {
                 errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
             });
             errorsHtml += '</ul></di>';

             $( '#form-errors' ).html( errorsHtml ); //appending to a <div id="form-errors"></div> inside form
           } else {
             /// do some thing else
           }*/
    }
});

In my controller I tried a few ways:

One:

public function saveAddr(Request $request)
{

  $this->validate($request->all(), [
     'addr_line_1' => 'required'
  ]);

Got error:

Type error: Argument 1 passed to App\Http \Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given,

Two:

$validation = Validator::make( $request->all(), [
            'addr_line_1' => 'required'
    ]);


    if( $validation->fails() )
    {

        return json_encode([
            'errors' => $validation->errors()->getMessages(),
            'code' => 422
        ]);
    }

    $data = array(
        'success' => true,
        'addr_line_1' => $request->input('addr_line_1'),
    );


    return response()->json();

Getting back: {"errors":{"addr_line_1":["The addr line 1 field is required."]},"code":422}

But Ajax goes into success

How can I catch the errors?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire