Laravel 11 Ajax Form Submit With Validation: A Seamless and Optimized Solution


In Laravel 11, leveraging Ajax for form submission with validation not only enhances user experience but also streamlines the validation process without the need for page reloads. In this blog, we'll explore a seamless and optimized approach to implementing Ajax form submission with validation in Laravel 11, ensuring smooth user interactions and efficient error handling.


Prerequisites


Before diving into the implementation, ensure you have the following prerequisites set up:


  • Laravel 11 project initialized and configured.
  • Basic knowledge of Laravel routing, controllers, views, and validation.


Step 1: Setting Up the Route


First, define a route to handle the form submission:


// routes/web.php


use App\Http\Controllers\FormController;


Route::post('submit-form', [FormController::class, 'submitForm'])->name('submit.form');


Step 2: Creating the Form View


Next, create a form view using Blade syntax:


<!-- resources/views/form.blade.php -->


<form id="myForm">

    @csrf

    <input type="text" name="name" id="name" placeholder="Enter your name">

    <span id="name-error" class="text-danger"></span><br>

    <input type="email" name="email" id="email" placeholder="Enter your email">

    <span id="email-error" class="text-danger"></span><br>

    <button type="submit" id="submitForm">Submit</button>

</form>


<div id="success-message" style="display: none;">Form submitted successfully!</div>


Step 3: Writing the Controller Logic


Create a controller to handle the form submission and validation:


// app/Http/Controllers/FormController.php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Validator;


class FormController extends Controller

{

    public function submitForm(Request $request)

    {

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

            'name' => 'required|string|max:255',

            'email' => 'required|email|max:255',

        ]);


        if ($validator->fails()) {

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

        }


        // Process form submission

        // Example: $form = new Form(); $form->name = $request->name; ...


        return response()->json(['success' => 'Form submitted successfully!']);

    }

}


Step 4: Writing the Ajax Script


Finally, write the JavaScript code to handle the form submission via Ajax:


// public/js/custom.js


$(document).ready(function() {

    $('#myForm').submit(function(e) {

        e.preventDefault();

        

        $.ajax({

            url: "{{ route('submit.form') }}",

            method: 'POST',

            data: $(this).serialize(),

            success: function(response) {

                if (response.errors) {

                    $('#name-error').text(response.errors.name);

                    $('#email-error').text(response.errors.email);

                } else {

                    $('#name-error').text('');

                    $('#email-error').text('');

                    $('#success-message').show();

                    $('#myForm')[0].reset();

                }

            }

        });

    });

});


Conclusion


Implementing Ajax form submission with validation in Laravel 11 can significantly enhance the user experience by providing real-time feedback and avoiding unnecessary page reloads. By following the steps outlined in this blog, you can seamlessly integrate Ajax functionality into your Laravel applications while ensuring efficient validation and error handling. Embrace the power of Laravel 11 and Ajax to create dynamic and responsive forms that delight users and streamline your development workflow. Happy coding!