Laravel 8 Ajax Form Validation Example
Jun 04, 2021 . Admin
Hi Dev,
Today, In this tutorial,i will explain how you can use and submit the form using ajax with jquery validation in laravel 8. we can ajax submit form after validation in laravel 8. you can easily laravel ajax form submit.
Now, you can submit the form using jquery and without the page refresh. When we submit an ajax form in laravel, we will add csrf token in ajax request.
In this article i will share you how to utilize laravel default validation with jquery ajax. Here we also print laravel validation message when false. So if you want 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 RouteIn 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\CategoriesController; 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', [CategoriesController::class, 'create'])->name('category.create'); Route::post('ajax-validation-store', [CategoriesController::class, 'store'])->name('ajax.validation.store');Step 2: Create Controller
In this second step we will now we should create new controller as CategoriesController. So run bellow command and create new controller.
php artisan make:controller CategoriesController
After you create successfully CategoriesController above command you will find new file in this path app/Http/Controllers/CategoriesController.php.
In this CategoriesController 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 CategoriesController.php file.
Path : app/Http/Controllers/CategoriesController.php<?php namespace App\Http\Controllers; use Illuminate\Routing\Controller; use Illuminate\Http\Request; use Validator; class CategoriesController extends Controller { /** * Write code on Method * * @return response() */ public function create() { return view('category.ajax-validation'); } /** * Write code on Method * * @return 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 class="bg-dark"> <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 - MyWebTuts.com</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...