Laravel 9 Form Submit Using jQuery Ajax Example

This tutorial demonstrates how to submit a form in Laravel 9 using jQuery Ajax with client-side validation. The default form processing method involves sending form data to the server via POST or GET, but Ajax is a preferred method for submitting forms using JavaScript or XHR.

To accomplish this, follow the steps below:

Laravel 9 Form Submit Using jQuery Ajax Example

Use the following steps to submit or send form data using jQuery ajax with validation in laravel 9 apps:

  • Download and install Laravel 9 by running the command “composer create-project –prefer-dist laravel/laravel LaravelAjax” in the terminal.
  • Configure the database details in the .env file.
  • Create the Contact model and migration using the command “php artisan make:model Contact -m” and update the create_contacts_table.php file with the necessary fields.
  • Create the Contact Us routes in the web.php file.
  • Create the AjaxContactController using the command “php artisan make:controller AjaxContactController” and update the code in the file with the necessary functions.
  • Create the Contact Us form in the Blade file and add jQuery and Ajax code to validate the form and submit it to the server.
  • Run the development server using the command “php artisan serve” and open the URL “http://127.0.0.1:8000/ajax-form” in your browser to submit the form.

Step 1 – Download Laravel 9 Application

First of all download or install laravel 9 new setup. So, open terminal and type the following command to install new laravel 9 app into your machine:

composer create-project --prefer-dist laravel/laravel LaravelAjax

This will create a new Laravel 9 application named “LaravelAjax” in your current directory. The “–prefer-dist” option tells Composer to download and install the application using the distribution package, rather than the source code.

Step 2 – Configure Database with App

In this step, setup database with your downloded/installed laravel 9 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Create Contact us Model & Migration

In this step, open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Contact -m

After that, open create_contacts_table.php file inside FormValidation/database/migrations/ directory. And the update the function up() with following code:

    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->text('message');
            $table->timestamps();
        });
    }

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

Step 4 – Create Contact Us Routes

In this step, open web.php file from routes direcotry. And update the following routes into web.php file:

use AppHttpControllersAjaxContactController;

Route::get('ajax-form', [AjaxContactController::class, 'index']);
Route::post('store-data', [AjaxContactController::class, 'store']);

Step 5 – Create Contact us Controller By Artisan Command

In this step, run the following command on command prompt to create controller file:

php artisan make:controller AjaxContactController

After that, go to app/http/controllers and open AjaxContactController.php file. And update the following code into it:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsContact;


class AjaxContactController extends Controller
{
    public function index()
    {
        return view('ajax-contact-us-form');
    }

    public function store(Request $request)
    {
        
        $validatedData = $request->validate([
          'name' => 'required',
          'email' => 'required|unique:employees|max:255',
          'message' => 'required'
        ]);

        $save = new Contact;

        $save->name = $request->name;
        $save->email = $request->email;
        $save->message = $request->message;

        $emp->save();

        return redirect('form')->with('status', 'Ajax Form Data Has Been validated and store into database');

    }
}

Step 6 – Create Contact Us Form in Blade File

Now, Go to resources/views and create ajax-contact-us-form.blade.php. Then create one contact us form with name, email and message fields.

We have created an ajax contact us form, so, you can update the following code into ajax-contact-us-form.blade.php file:

<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Ajax Form Submit using jQuery Validation - Tutsmake.com</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<style>
.error{
color: #FF0000; 
}
</style>
</head>
<body>
<div class="container mt-4">
<div class="card">
<div class="card-header text-center font-weight-bold">
<h2>Laravel 9 Ajax Post Form Data on Controller with jQuery Validation Example - Tutsmake.com</h2>
</div>
<div class="card-body">
<form name="contactUsForm" id="contactUsForm" method="post" action="javascript:void(0)">
@csrf
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" id="name" name="name" class="form-control">
</div>          
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" id="email" name="email" class="form-control">
</div>           
<div class="form-group">
<label for="exampleInputEmail1">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
</div>
</div>	
<script>
if ($("#contactUsForm").length > 0) {
$("#contactUsForm").validate({
rules: {
name: {
required: true,
maxlength: 50
},
email: {
required: true,
maxlength: 50,
email: true,
},  
message: {
required: true,
maxlength: 300
},   
},
messages: {
name: {
required: "Please enter name",
maxlength: "Your name maxlength should be 50 characters long."
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},   
message: {
required: "Please enter message",
maxlength: "Your message name maxlength should be 300 characters long."
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').html('Please Wait...');
$("#submit"). attr("disabled", true);
$.ajax({
url: "{{url('store-data')}}",
type: "POST",
data: $('#contactUsForm').serialize(),
success: function( response ) {
$('#submit').html('Submit');
$("#submit"). attr("disabled", false);
alert('Ajax form has been submitted successfully');
document.getElementById("contactUsForm").reset(); 
}
});
}
})
}
</script>
</body>
</html>

The following below jQuery and ajax code will validate form data before submitting/posting form data on the controller in laravel:

<script>
if ($("#contactUsForm").length > 0) {
$("#contactUsForm").validate({
rules: {
name: {
required: true,
maxlength: 50
},
email: {
required: true,
maxlength: 50,
email: true,
},  
message: {
required: true,
maxlength: 300
},   
},
messages: {
name: {
required: "Please enter name",
maxlength: "Your name maxlength should be 50 characters long."
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},   
message: {
required: "Please enter message",
maxlength: "Your message name maxlength should be 300 characters long."
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').html('Please Wait...');
$("#submit"). attr("disabled", true);
$.ajax({
url: "{{url('store')}}",
type: "POST",
data: $('#contactUsForm').serialize(),
success: function( response ) {
$('#submit').html('Submit');
$("#submit"). attr("disabled", false);
alert('Ajax form has been submitted successfully');
document.getElementById("contactUsForm").reset(); 
}
});
}
})
}
</script>

Step 7 – Run Development Server

Last step, open command prompt and run the following command to start developement server:

php artisan serve

Then open your browser and hit the following url on it:

http://127.0.0.1:8000/ajax-form