Laravel Ajax Form Validation Example

To create an Ajax validation in Laravel, use the “default validation with jquery Ajax.” Laravel provides an easy way to use validation without Ajax, but if you want to use Laravel validation with jquery. This is because the server checks all the input fields against defined validation, and if any of the validation fails, it will redirect to our create page with error messages.

Here are the steps to validate the Ajax form in Laravel:

Step 1: Set up Laravel Configuration.

composer create-project laravel/laravel laravelajaxvalidation --prefer-dist

After Setup Laravel Configuration, We can define routes, models, and a controller for the next step.

Step 2: Define the model, controller, and routes.

Type the following command to generate a model and controller.

php artisan make:model Form

php artisan make:controller FormController

It will create two files.

  1. Form.php
  2. FormController.php

Now we can define routes.

Follow routes  >>  web.php file and define the following routes.

// web.php

Route::get('form','FormController@create');
Route::post('form','FormController@store');

In the FormController, define a function, and write the following code.

// FormController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('create');
    }

Generate a create.blade.php file inside the views folder.

<html lang="en">
<head>
	<title>Laravel Ajax Validation Tutorial</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>


<div class="container">
	    <h3 class="jumbotron">Laravel Ajax Validation</h3>
	<form>
		<div class="form-group">
			<label>Footballer Name</label>
			<input type="text" name="footballername" class="form-control" placeholder="Enter Footballer Name" id="footballername">
		</div>


		<div class="form-group">
			<label>Club</label>
			<input type="text" name="club" class="form-control" placeholder="Enter Club" id="club">
		</div>


		<div class="form-group">
			<strong>Country</strong>
			<input type="text" name="country" class="form-control" placeholder="Enter Country" id="country">
		</div>


		<div class="form-group">
			<button class="btn btn-success" id="submit">Submit</button>
		</div>
	</form>
</div>

</body>
</html>

laravel 5.5 validation with ajax

Step 3: Add jQuery code.

Include jQuery.ajax() function to submit the request to the server with all input fields in that click event.

<script type="text/javascript">

         jQuery(document).ready(function(){
            jQuery('#submit').click(function(e){
               e.preventDefault();
               jQuery.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/form') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#footballername').val(),
                     type: jQuery('#club').val(),
                     price: jQuery('#country').val()
                  },
                  success: function(data){
                  		jQuery.each(data.errors, function(key, value){
                  			jQuery('.alert-danger').show();
                  			jQuery('.alert-danger').append('<p>'+value+'</p>');
                  		});
	            	}
	                
                  });
               });
            });
</script>

Add jQuery code into create.blade.php

//create.blade.php
<html lang="en">
<head>
	<meta name="_token" content="{{csrf_token()}}" />
	<title>Laravel Ajax Validation Example</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>


<div class="container">
	    <h3 class="jumbotron">Laravel Ajax Validation</h3>
	    <div class="alert alert-danger" style="display:none"></div>
	<form>
		<div class="form-group">
			<label>Footballer Name</label>
			<input type="text" name="footballername" class="form-control" placeholder="Enter Footballer Name" id="footballername">
		</div>


		<div class="form-group">
			<label>Club</label>
			<input type="text" name="club" class="form-control" placeholder="Enter Club" id="club">
		</div>


		<div class="form-group">
			<strong>Country</strong>
			<input type="text" name="country" class="form-control" placeholder="Enter Country" id="country">
		</div>


		<div class="form-group">
			<button class="btn btn-success" id="submit">Submit</button>
		</div>
	</form>
</div>

<script type="text/javascript">

         jQuery(document).ready(function(){
            jQuery('#submit').click(function(e){
               e.preventDefault();
               jQuery.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/form') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#footballername').val(),
                     type: jQuery('#club').val(),
                     price: jQuery('#country').val()
                  },
                  success: function(data){
                  		jQuery.each(data.errors, function(key, value){
                  			jQuery('.alert-danger').show();
                  			jQuery('.alert-danger').append('<p>'+value+'</p>');
                  		});
	            	}
	                
                  });
               });
            });
</script>

</body>
</html>

Step 4: Write the store function to store the data

Move to the FormController.php file and add the following code.

//FormController.php

 public function store(Request $request)
    {
        $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']);
        
 }

Step 5: Display Error

If you click submit button and all field is blank, then display an error.

Laravel AJAX Validation

That’s it.

6 thoughts on “Laravel Ajax Form Validation Example”

  1. hey 🙂 this is awesome stuff <3 I just wanted to know if you are aware that that when the submit button is clicked(without filling the inputs) many times consecutively, the error message is keep on repeating below the other. How to overcome this?

    Reply
  2. return response()->json([‘success’=>’Record is successfully added’]);
    HOw I can manage my success in jquery file. Becuase we are only printing errors not sucess

    Reply
  3. There is an error in the code, specifically in the sending part of the parameters:

    data: {
                          name: jQuery (‘# footballername’). val (),
                          type: jQuery (‘# club’). val (),
                          price: jQuery (‘# country’). val ()
                       },

    when it should be
    data: {
                          footballername: jQuery (‘# footballername’). val (),
                          club: jQuery (‘# club’). val (),
                          country: jQuery (‘# country’). val ()
                       },

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.