How to validate input data using ajax in laravel How to validate input data using ajax in laravel php php

How to validate input data using ajax in laravel


Your approach is actually not wrong, it just you need to catch the error response on your ajax request whereas, when Laravel validation fails, it throws an Error 422 (Unprocessable Entity) with corresponding error messages.

/**Ajax code**/$.ajax({    type: "post",    url: "{{ url('/verifydata') }}",    data: {name: name,  _token: token},    dataType: 'json',              // let's set the expected response format    success: function(data){         //console.log(data);         $('#success_message').fadeIn().html(data.message);    },    error: function (err) {        if (err.status == 422) { // when status code is 422, it's a validation issue            console.log(err.responseJSON);            $('#success_message').fadeIn().html(err.responseJSON.message);                        // you can loop through the errors object and show it to the user            console.warn(err.responseJSON.errors);            // display errors on each form field            $.each(err.responseJSON.errors, function (i, error) {                var el = $(document).find('[name="'+i+'"]');                el.after($('<span style="color: red;">'+error[0]+'</span>'));            });        }    }});/**Ajax code ends**/   

On your controller

public function testAjax(Request $request){    // this will automatically return a 422 error response when request is invalid    $this->validate($request, ['name' => 'required']);    // below is executed when request is valid    $name = $request->name;    return response()->json([         'message' => "Welcome $name"    ]);  }


Here's a better approach to validation:

In your controller:

public function testAjax(Request $request){   $this->validate($request, [ 'name' => 'required' ]);   return response("welcome ". $request->input('name'));}

The framework then will create a validator for you and validate the request. It will throw a ValidationException if it fails validation.

Assuming you have not overriden how the validation exception is rendered here's the default code the built-in exception handler will run

protected function convertValidationExceptionToResponse(ValidationException $e, $request){        if ($e->response) {            return $e->response;        }        $errors = $e->validator->errors()->getMessages();        if ($request->expectsJson()) {            return response()->json($errors, 422);        }        return redirect()->back()->withInput($request->input())->withErrors($errors);}

Again this is handled for you by the framework.

On the client side you should be able to do:

<script>  $(document).ready(function(){      $("#submit").click(function(){        var name = $("#name").val();        var token = $("#token").val();        /**Ajax code**/        $.ajax({           type: "post",           url:"{{URL::to('/verifydata')}}",           data:{name:name,  _token: token},           success:function(data){              //console.log(data);              $('#success_message').fadeIn().html(data);           },           error: function (xhr) {               if (xhr.status == 422) {                   var errors = JSON.parse(xhr.responseText);                   if (errors.name) {                       alert('Name is required'); // and so on                   }               }           }        });          /**Ajax code ends**/          });  });</script>


best way for handle in php controller :

        $validator = \Validator::make($request->all(), [        'footballername' => 'required',        'club' => 'required',        'country' => 'required',    ]);        if ($validator->fails())    {        return response()->json(['errors'=>$validator->errors()->all()]);    }    return response()->json(['success'=>'Record is successfully added']);