Laravel 12 Ajax Form Validation Using jQuery

Hi there! As a web developer, I love creating smooth and user-friendly web applications. One feature that makes forms more interactive is validating user input without refreshing the page. In this article, I’ll walk you through how to set up Ajax form validation in Laravel 12 using jQuery.

Laravel is a powerful PHP framework, and combining it with Ajax and jQuery allows us to validate forms dynamically, improving the user experience. Whether you’re new to Laravel or looking to enhance your skills, this guide is simple, beginner-friendly, and packed with practical steps.

Step-by-Step Guide to Ajax Form Validation in Laravel 12 Using jQuery

Laravel 12 Ajax Form Validation Using jQuery

Step 1: Set Up a Laravel 12 Project

First, I need to create a new Laravel 12 project. I’ll open my terminal and run the following command to install Laravel:

composer create-project laravel/laravel laravel-ajax-validation

Once the installation is complete, I navigate to the project folder and ensure my local server (like Laravel’s Artisan server) is running:

cd laravel-ajax-validation
php artisan serve

I also set up a database in MySQL and update the .env file with my database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_ajax_validation
DB_USERNAME=root
DB_PASSWORD=

Step 2: Create a Model and Migration

Next, I’ll create a model and migration for a Post to store form data. In the terminal, I run:

php artisan make:model Post -m

This creates a Post model and a migration file. I open the migration file in database/migrations/ and define the schema for the posts table:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

I run the migration to create the table:

php artisan migrate

Step 3: Create Routes

I define two routes in routes/web.php: one to display the form and another to handle the Ajax form submission:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::post('/posts/store', [PostController::class, 'store'])->name('posts.store');

Step 4: Create the Controller

I create a PostController to handle the form logic:

php artisan make:controller PostController

In app/Http/Controllers/PostController.php, I add the following code:

<?php
namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|min:5|max:255',
            'description' => 'required|min:10',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        Post::create($request->all());
        return response()->json(['success' => 'Post created successfully!']);
    }
}

This controller validates the form data and returns JSON responses for Ajax.

Step 5: Create the Blade View

I create a Blade view file at resources/views/posts/index.blade.php to display the form and posts:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 12 Ajax Form Validation with jQuery</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <h2>Laravel 12 Ajax Form Validation</h2>
        <div class="card">
            <div class="card-body">
                <div class="alert alert-danger print-error-msg" style="display:none">
                    <ul></ul>
                </div>
                <div class="alert alert-success print-success-msg" style="display:none"></div>
                <form id="post-form">
                    @csrf
                    <div class="mb-3">
                        <label for="title" class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" id="title">
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea name="description" class="form-control" id="description"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
        <table class="table table-bordered mt-3">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                @foreach($posts as $post)
                <tr>
                    <td>{{ $post->id }}</td>
                    <td>{{ $post->title }}</td>
                    <td>{{ $post->description }}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
    <script>
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $(document).ready(function() {
            $('#post-form').on('submit', function(e) {
                e.preventDefault();
                let formData = {
                    title: $('#title').val(),
                    description: $('#description').val(),
                };

                $.ajax({
                    url: "{{ route('posts.store') }}",
                    type: 'POST',
                    data: formData,
                    success: function(data) {
                        $('.print-error-msg').hide();
                        $('.print-success-msg').show().html(data.success);
                        $('#post-form')[0].reset();
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    },
                    error: function(data) {
                        $('.print-success-msg').hide();
                        $('.print-error-msg').css('display', 'block');
                        $('.print-error-msg ul').html('');
                        $.each(data.responseJSON.errors, function(key, value) {
                            $('.print-error-msg ul').append('<li>' + value + '</li>');
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>

This view includes Bootstrap for styling, jQuery for Ajax, and a CSRF token for security.

Step 6: Test the Application

I start the server with php artisan serve and visit http://localhost:8000/posts. I fill out the form and submit it. If there are validation errors, they appear without refreshing the page. If the form is valid, the success message shows, and the table updates with the new post.

Conclusion

Implementing Ajax form validation in Laravel 12 using jQuery is straightforward and enhances the user experience by providing real-time feedback without page reloads. In this guide, I walked you through setting up a Laravel project, creating a model, defining routes, building a controller, and designing a form with jQuery Ajax.

FAQs

1. Why use Ajax for form validation in Laravel?
Ajax allows you to validate forms without refreshing the page, providing a smoother user experience and faster feedback on errors.

2. Do I need jQuery for Ajax in Laravel?
No, you can use other libraries like Axios or vanilla JavaScript, but jQuery is beginner-friendly and widely used for Ajax requests.

3. How does Laravel handle CSRF protection with Ajax?
Laravel requires a CSRF token for POST requests. You include it in the Ajax request using $.ajaxSetup with the token from a meta tag.

4. Can I customize validation messages in Laravel?
Yes, you can define custom messages in the Validator::make method or use a Form Request class for more complex validation logic.

5. What if my Ajax request fails?
Check the console for errors, ensure the CSRF token is included, and verify the route and controller logic. Laravel’s 422 response typically indicates validation errors.


You might also like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS