title: How to validate input data using ajax in laravel
body: <p><strong>testAjax function</strong> <em>inside</em> <strong>PostsController class</strong>:</p>
  
  <pre><code>public function testAjax(Request $request)
    {
      $name = $request-&gt;input('name');
      $validator = Validator::make($request-&gt;all(), ['name' =&gt; 'required']);
  
      if ($validator-&gt;fails()){
          $errors = $validator-&gt;errors();
          echo $errors;
      }
      else{
        echo "welcome ". $name;
      }
  
    }
  </code></pre>
  
  <p>inside <strong>web.php</strong> file:</p>
  
  <pre><code>Route::get('/home' , function(){
    return view('ajaxForm');
  });
  
  Route::post('/verifydata', 'PostsController@testAjax');
  </code></pre>
  
  <p><strong>ajaxForm.blade.php:</strong></p>
  
  <pre><code>&lt;script src="{{ asset('public/js/jquery.js') }}"&gt;&lt;/script&gt;
  
    &lt;input type="hidden" id="token" value="{{ csrf_token() }}"&gt;
    Name&lt;input type="text" name="name" id="name"&gt;
    &lt;input type="button" id="submit" class="btn btn-info" value="Submit" /&gt;
  &lt;script&gt;
    $(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**/    
        });
    });
  &lt;/script&gt;
  </code></pre>
  
  <p>So when click on submit button by entering some data then the output message(<em>echo "welcome ". $name;</em>) 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.
  <a href="https://i.stack.imgur.com/5HNOK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5HNOK.png" alt="enter image description here"></a>
  <a href="https://i.stack.imgur.com/SrTP0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SrTP0.png" alt="enter image description here"></a></p>