Hello developers! In this guide, we'll see the laravel 11 Ajax form submitted with validation.
Here, we'll learn about how to submit forms with Ajax and perform validation in Laravel 11. We'll submit a form without page refresh using jQuery Ajax.
In this article, we'll create a form and it will open when click on the Create button then send an Ajax form request, and validate the form data into the controller.
So, let's see AJAX form validation in laravel 11.
Step 1: Installing Laravel 11 Application
Step 2: Create Migration and Model
Step 3: Create a Controller
Step 4: Create a Routes
Step 5: Create Blade File
Step 6: Run the Laravel 11 App
Step 1: Installing Laravel 11 Application
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-ajax-form
Step 2: Create Migration and Model
Then, we'll create a migration using the following command.
php artisan make:migration create_posts_table
Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};
Next, we'll migrate the migration into the database using the following command.
php artisan migrate
Now, we'll create a Post.php model using the following command.
php artisan make:model Post
app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'title', 'body'
];
}
Step 3: Create a Controller
Then, we'll create a new PostController.php using the following command.
php artisan make:controller PostController
app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Post;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(): View
{
$posts = Post::get();
return view('posts', compact('posts'));
}
/**
* Write code on Method
*
* @return response()
*/
public function store(Request $request): JsonResponse
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
Post::create([
'title' => $request->title,
'body' => $request->body,
]);
return response()->json(['success' => 'Post created successfully.']);
}
}
Step 4: Create Routes
Then, we'll define the routes in the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('posts', [ PostController::class, 'index' ]);
Route::post('posts', [ PostController::class, 'store' ])->name('posts.store');
Step 5: Create Blade File
Now, we'll create a posts.blade.php file. In this file, we'll create a form and send an AJAX jQuery request.
resources/views/posts.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Ajax Form Submit With Validation - Techsolutionstuff</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Ajax Form Submit With Validation - Techsolutionstuff</h3>
<div class="card-body">
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Posts
<button type="button" class="btn btn-success float-end" data-bs-toggle="modal" data-bs-target="#postModal"><i class="fa fa-plus"></i>
Create Post
</button>
</th>
</tr>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
@foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->body }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="postModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create Post</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="ajax-form" action="{{ route('posts.store') }}">
@csrf
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3">
<label for="titleID" class="form-label">Title:</label>
<input type="text" id="titleID" name="title" class="form-control" placeholder="Name">
</div>
<div class="mb-3">
<label for="bodyID" class="form-label">Body:</label>
<textarea name="body" class="form-control" id="bodyID"></textarea>
</div>
<div class="mb-3 text-center">
<button class="btn btn-success btn-submit"><i class="fa fa-save"></i> Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$('#ajax-form').submit(function(e) {
e.preventDefault();
var url = $(this).attr("action");
let formData = new FormData(this);
$.ajax({
type:'POST',
url: url,
data: formData,
contentType: false,
processData: false,
success: (response) => {
info('Form submitted successfully');
$('#postModal').hide();
},
error: function(response){
$('#ajax-form').find(".print-error-msg").find("ul").html('');
$('#ajax-form').find(".print-error-msg").css('display','block');
$.each( response.responseJSON.errors, function( key, value ) {
$('#ajax-form').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
</script>
</html>
Step 6: Run the Laravel 11 Application
Next, run the laravel 11 application using the following command.
php artisan serve
You might also like:
Read Also: How to Create AJAX CRUD Operation in Laravel 11
Read Also: Laravel 10 Datatable Date Range Filter using AJAX
Top comments (0)