AppDividend
Latest Code Tutorials

Laravel Ajax Validation Tutorial From Scratch

0 3,503

Get real time updates directly on you device, subscribe now.

Laravel Ajax Validation Tutorial From Scratch is today’s leading topic.We will build a simple ajax validation using Laravel 5.5. Laravel provides an easy way to use validation without ajax, But if you want to use Laravel validation with jquery then you can’t do it quickly. The server checks all the input field against defined validation, and if any of the validation fails, it will redirect to our create page with error messages.

Laravel Ajax Validation Tutorial

First, we will install the laravel and then configure it.

Step 1: Setup Laravel Configuration.

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

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

Step 2: Define model, controller, and routes.

Type the following command to generate model and controller.

php artisan make:model Form

php artisan make:controller FormController

It will create two files.

  1. Form.php
  2. FormController.php
Related Posts
1 of 34

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‘s define a function, write the following code.

// FormController.php

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

Now, generate a create.blade.php file inside 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.

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

<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 error.

Laravel AJAX Validation

So, our Laravel Ajax Validation Tutorial is over.

 

 

Leave A Reply

Your email address will not be published.