In this article, I'll demonstrate how to use Laravel 9 to submit a form using ajax and jQuery validation. In Laravel 9, we may ajax submit a form following validation. Laravel's ajax form validation is simple.

Using jQuery, you may submit the form without refreshing the entire page. In Laravel 9, the csrf token is included to the ajax request when an ajax form is submitted.

I'll demonstrate how you leverage the default Laravel validation with jQuery Ajax in this example. Here, we also display a false validation message from Laravel. Thus, you are in the ideal place if you wish to use ajax form validation in a Laravel application.

Simply follow the steps below to build an example of ajax validation:

Download Laravel

Installing a fresh Laravel application will kick off the tutorial. If the project has already been created, skip the next step.

composer create-project laravel/laravel example-app

Add Route

We will initially establish two new routes for demonstration purposes. so add the following route by opening your routes/web.php file.

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');

Add Controller

At this stage, a new controller named PostController should be created. Run the command below to create a new controller.

php artisan make:controller PostController

You may find the new file in the directory app/Http/Controllers/PostController.php by running the command below.

We will implement the following two ajax view and post methods in this controller:

  1. ajaxValidation()
  2. ajaxValidationStore()

Let's copy the code below and paste it into the 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()]);
    }

}

Add Blade File

In the final phase, let's build ajaxValidation.blade.php for the layout and include the following code for the design and jQuery ajax:

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

Once all the steps have been completed, input the command and press Enter to launch the Laravel application:

php artisan serve

You must now launch a web browser, enter the provided URL, and then view the app's output:

http://localhost:8000/ajax/validation

Tags

Recommended Posts

View All

Google Map with Multiple Marker and Info Box in Laravel


This tutorial will teach you how to use Laravel to integrate a Google Map with numerous markers and an info box.

Laravel 9 Send SMS Notification to Mobile Phone Tutorial


Learn how to use the Vonage (nexmo) package in a Laravel application to send an SMS notice to a mobile phone.

How to Create REST API in Laravel7 using Passport


rest api in laravel 7/6 step by step, rest api in laravel 7/6 tutorial, laravel 7/6 restful api authentication, laravel 7/6 passport rest api tutorial

Laravel 9 Add Watermark on Image


In this article, we'll show you how to use the Laravel application to apply a text overlay watermark on an image.

Laravel 9 Install React Auth Tutorial with Example


In this article, I'll demonstrate how to use the Laravel UI and React Auth scaffolding to create login, register, logout, forget password, profile, an...