Laravel 9 Ajax Form Validation Example

10-Apr-2023

.

Admin

Laravel 9 Ajax Form Validation Example

Hi Guys,

In this tutorial,i will shows how you can submit the form using ajax with jquery validation in laravel 9. we can ajax submit form after validation in laravel 9. you can easy laravel ajax form submit.

you can submit the form using jquery and without the whole page refresh. When we submit an ajax form in laravel 9, we will add csrf token in ajax request.

In this example i will show you how to use 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.

Just follow bellow step to create ajax validation example:

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Add Route

In first step we will create new two routes for demo. so open your routes/web.php file and add following route.

routes/web.php

<?php

use App\Http\Controllers\PostController;

/*

|--------------------------------------------------------------------------

| 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, 'ajaxValidation'])->name('ajax.validation');

Route::post('ajax/validation/store', [PostController::class, 'ajaxValidationStore'])->name('ajax.validation.store');

Step 3: Add Controller

In this point, now we should create new controller as PostController. So run bellow command and create new controller.

php artisan make:controller PostController

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

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

1)ajaxValidation()

2)ajaxValidationStore()

So, let's copy bellow code and put on PostController.php file.

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 ajaxValidation()

{

return view('post.ajaxValidation.ajaxValidation');

}

/**

* Display a listing of the myformPost.

*

* @return \Illuminate\Http\Response

*/

public function ajaxValidationStore(Request $request)

{

$validator = Validator::make($request->all(), [

'pswd' => 'required',

'email' => 'required|email',

'address' => 'required',

]);

if ($validator->passes()) {

return response()->json(['success'=>'Added new records.']);

}

return response()->json(['error'=>$validator->errors()]);

}

}

Step 4: Add Blade File

In Last step, let's create ajaxValidation.blade.php for layout and we will write design code and jquery ajax code,so put following code:

resources/views/post/ajaxValidation/ajaxValidation.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

<title>Ajax Validation Laravel 9</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" style="margin-top: 100px;">

<h2>Ajax Validation form Laravel 9</h2>

<form>

@csrf

<div class="form-group">

<label for="email">Email:</label>

<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">

<span class="text-danger error-text email_err"></span>

</div>

<div class="form-group">

<label for="pwd">Password:</label>

<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pswd">

<span class="text-danger error-text pswd_err"></span>

</div>

<div class="form-group">

<label for="address">Address:</label>

<textarea class="form-control" name="address" id="address" placeholder="Address"></textarea>

<span class="text-danger error-text address_err"></span>

</div>

<button type="submit" class="btn btn-primary btn-submit">Submit</button>

</form>

</div>

<script type="text/javascript">

$(document).ready(function() {

$(".btn-submit").click(function(e){

e.preventDefault();

var _token = $("input[name='_token']").val();

var email = $("#email").val();

var pswd = $("#pwd").val();

var address = $("#address").val();

$.ajax({

url: "{{ route('ajax.validation.store') }}",

type:'POST',

data: {_token:_token, email:email, pswd:pswd,address:address},

success: function(data) {

console.log(data.error)

if($.isEmptyObject(data.error)){

alert(data.success);

}else{

printErrorMsg(data.error);

}

}

});

});

function printErrorMsg (msg) {

$.each( msg, function( key, value ) {

console.log(key);

$('.'+key+'_err').text(value);

});

}

});

</script>

</body>

</html>

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/ajax/validation

Output :

It will help you...

#Laravel 9