How to validate input data using ajax in laravel
Asked Answered
Z

5

13

testAjax function inside PostsController class:

public function testAjax(Request $request)
  {
    $name = $request->input('name');
    $validator = Validator::make($request->all(), ['name' => 'required']);

    if ($validator->fails()){
        $errors = $validator->errors();
        echo $errors;
    }
    else{
      echo "welcome ". $name;
    }

  }

inside web.php file:

Route::get('/home' , function(){
  return view('ajaxForm');
});

Route::post('/verifydata', 'PostsController@testAjax');

ajaxForm.blade.php:

<script src="{{ asset('public/js/jquery.js') }}"></script>

  <input type="hidden" id="token" value="{{ csrf_token() }}">
  Name<input type="text" name="name" id="name">
  <input type="button" id="submit" class="btn btn-info" value="Submit" />
<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);
            }
          });
          /**Ajax code ends**/    
      });
  });
</script>

So when click on submit button by entering some data then the output message(echo "welcome ". $name;) is printing. But when I click on submit button with empty text box then it does not print the error message from the controller and it throws a 422 (Unprocessable Entity) error in console. Why my approach is wrong here and how can I print the error message then. Please help. Thank you in advance. enter image description here enter image description here

Zoosporangium answered 17/3, 2018 at 7:55 Comment(3)
Send json data from laravel and read from ajax responseBullfinch
Laravel already sends a good error response all you need to do is handle errors in the client-sideAnnabellannabella
I would suggest you use axios and Vue.js to do it. very easy. You can send the data the laravel, and in the controller, you make if(request()->wantsJson()) and you return the data. then in the frontend, you catch it. and display on the screen. it may seem hard, but it is really 1 minute of work.Damned
P
27

Your approach is actually not wrong, it's 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"
    ]);

  }
Piotrowski answered 17/3, 2018 at 8:6 Comment(1)
This is great. The only thing I don't like is that the error is shown multiple times when the error persists and the user presses the submit button again.Maugre
A
4

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>
Annabellannabella answered 17/3, 2018 at 8:36 Comment(0)
H
3

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']);
Hygroscopic answered 3/3, 2021 at 7:40 Comment(0)
C
1

The code for form validation in Vannilla Javascript

const form_data = new FormData(document.querySelector('#form_data'));
fetch("{{route('url')}}", {
       'method': 'post',
       body: form_data,
 }).then(async response => {
      if (response.ok) {
         window.location.reload();
      }
      const errors = await response.json();
      var html = '<ul>';
      for (let [key, error] of Object.entries(errors)) {
          for (e in error) {
              html += `<li>${error[e]}</li>`;
          }
      }
      html += '</ul>';
      //append html to some div

      throw new Error("error");
  })
  .catch((error) => {
     console.log(error)
  });

Controller

use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
    'file' => 'image|mimes:jpeg,png,jpg|max:1024',
    'field1' => 'required',
    'field2' => 'required'
   ];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
   return response()->json($validator->errors(), 400);
}
session()->flash('flash', ['status' => 'status', 'message' => 'message']);
Confederacy answered 3/3, 2022 at 6:55 Comment(0)
T
0

Jquery Code:

  let first_name=     $('.first_name').val();
            let last_name=      $('.last_name').val();
            let email=     $('.email').val();
            let subject=      $('.subject').val();
            let message=        $('.message').val();

    $('.show-message').empty();

    console.log('clicked');
    $.ajax({
        type : 'POST',
        url  : '{{route("contact-submit")}}',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            first_name,
            last_name,
            email,
            subject,
            message,
        },
        success: function(data) {

            console.log('data',data);
            $('.show-message').html('Form Submitted');
        },

        error :  function(data,data2,data3)
        {

            let response=data.responseJSON;
            let all_errors=response.errors;

            console.log('all_errors',all_errors);

            $.each(all_errors,function(key,value){
                $('.show-message').append(`<p>${value}</p>`);
            });


        }
    });

Controller Code:

$validator=Validator::make($request->all(),[
                'first_name'=>'required',
                'last_name'=>'required',
                'email'=>'required|email',
                'subject'=>'required',
                'message'=>'required',
            ]);

        if($validator->fails())
        {
            return response()->json([
                'success'=>false,
                'errors'=>($validator->getMessageBag()->toArray()),
            ],400);
        }

        return response()->json([
            'success'=>true,
        ],200);

See More Details at: https://impulsivecode.com/validate-input-data-using-ajax-in-laravel/

Trapezium answered 9/12, 2022 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.