Laravel ajax validation
To create an ajax validation, use the Laravel 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.
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, models, and a controller for the next step.
Step 2: Define 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.
- Form.php
- 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‘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 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>
Step 3: Add jQuery code.
Now, include jQuery.ajax() function in that click event to submit the request to the server with all input fields.
<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.
So, our Laravel 9 Ajax Validation Example is over.
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?
add
jQuery(‘.alert-danger’).empty();
first line in the success of your jquery script.
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
use jQuery(‘.alert-danger’).html(”); before jQuery(‘.alert-danger’).append(”+value+”);
It’s not work.
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 ()
},