Laravel 9 jquery ajax form submit with validation; In this tutorial, we will learn how to submit or post form data on the controller or server using jQuery ajax with validation (client-side) in laravel 9 apps.
Submitting forms via Ajax. The default mechanism for form processing relies on standard HTML style form submission that causes the contents of an HTML form to be sent to the server via either POST or GET (default is POST ). This is where a form submitted via JavaScript using Ajax or XHR is the preferred option.
How to Form Submit Form using jQuery Ajax in Laravel 9
Use the following steps to submit or send form data using jQuery ajax with validation in laravel 9 apps:
- Step 1 – Download Laravel 9 Application
- Step 2 – Configure Database with App
- Step 3 – Create Contact us Model & Migration
- Step 4 – Create Contact us Routes
- Step 5 – Create Contact us Controller By Artisan Command
- Step 6 – Create Contact us form in Blade File
- Step 7 – Run Development Server
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
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 App\Http\Controllers\AjaxContactController;
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 App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Contact;
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:contacts|max:255',
'message' => 'required'
]);
$save = new Contact;
$save->name = $request->name;
$save->email = $request->email;
$save->message = $request->message;
$save ->save();
return redirect('ajax-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
Recommended Laravel Tutorials