Laravel 9 Ajax Form Validation Tutorial

Hi Artisan,

In this post,i will apportion you how you can utilize and submit the form utilizing ajax with jquery validation in laravel 8. we can ajax submit form after validation in laravel 8. you can facilely laravel ajax form submit.

Now, you can submit the form utilizing jquery and without the page refresh. When we submit an ajax form in laravel, we will integrate csrf token in ajax request.

In this article i will apportion you how to utilize laravel default validation with jquery ajax. Here we withal print laravel validation message when erroneous. So if you optate to ajax form validation in laravel app then you are right place.

Here,you can just follow bellow all step to create ajax validation example:

Step 1: Add Route

In this first step we will engender two routes. so open your routes/web.php file and add following route.

Path : routes/web.php
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('ajax/validation', [PostController::class, 'create'])->name('category.create');
Route::post('ajax/validation/store', [PostController::class, 'store'])->name('ajax.validation.store');
Step 2: Create Controller

In this second step we will now we should create new controller as PostController. So run bellow command and create new controller.

php artisan make:controller PostController

After you create successfully PostController above command you will find new file in this path app/Http/Controllers/PostController.php.

In this PostController we will write two method for ajax view and post as listed bellow methods:

  • create()
  • store()
  • So, let's copy bellow code and put on PostController.php file.

    Path : app/Http/Controllers/PostController.php
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Routing\Controller;
    use Illuminate\Http\Request;
    use Validator;
    
    class PostController extends Controller
    {
    	/**
         * Display a listing of the myformPost.
         *
         * @return \Illuminate\Http\Response
         */
    	public function create()
    	{
            return view('category.ajax-validation');
    	}
    
    	/**
         * Display a listing of the myformPost.
         *
         * @return \Illuminate\Http\Response
         */
        public function store(Request $request)
        {
        	$validator = Validator::make($request->all(),[
                'name' => 'required',
                'description' => 'required',
            ]);
    
            if (!$validator->passes()) {
                return response()->json(['error'=>$validator->errors()->all()]);
            }
        
            $input = $request->all();
            Category::create($input);        
    
            return response()->json(['success'=>'Category saved successfully.']);
        }
    
    }
    
    Step 3: Create View File

    Inside Last step, let's engender ajax-validation.blade.php for layout and we will write design code and jquery ajax code,so put my following code:

    Path : resources/views/category/ajax-validation.blade.php
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Ajax Validation Laravel 8</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    </head>
    <body>
    
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header">
                        <h4>Laravel 8 Ajax Validation - CodingTracker</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-danger error-msg" style="display:none">
                            <ul></ul>
                        </div>
                        <form action="" id="createmodal" name="catmodal" class="form-horizontal">
                        {{ csrf_field() }}
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="cname">Name</label>
                                        <input type="text" class="form-control" name="name" id="name" placeholder="Category Name..">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="cdes">Description</label>
                                        <textarea class="form-control" id="description" name="description" rows="3" placeholder="Category Description.."></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <button class="btn btn-success mt-2" type="submit" id="savebtn">Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script type="text/javascript">
        $(document).ready(function() {
            $('body').on('click','#savebtn',function(e){
                e.preventDefault();
                var _token = $("input[name='_token']").val();
                var name = $('#name').val();
                var description = $('#description').val();
                $.ajax({
                    type:'POST',
                    url:'{{ route('ajax.validation.store') }}',
                    dataType: 'json',
                    data:{
                        _token:_token,
                        name:name,
                        description:description,
                    },
                    success:function (data) {
                        if ($.isEmptyObject(data.error)) {
                            alert(data.success);
                            $('#name').val('');
                            $('#description').val('');
                        }else{
                            printErrorMsg(data.error)
                        }
                        table.draw();
                    }
                });
            });
    
            function printErrorMsg(msg) {
                $('.error-msg').find('ul').html('');
                $('.error-msg').css('display','block');
                $.each( msg, function( key, value ) {
                    $(".error-msg").find("ul").append('<li>'+value+'</li>');
                });
            }
        });
    </script>
    
    </body>
    </html>
    
    Preview

    It will help you...

    Post a Comment