Laravel 10 Ajax Request Example Tutorial
Hi Artisan,
This tutorial will give you an example of laravel 10 ajax request example. if you want to see an example of how to use ajax in laravel 10 then you are in the right place. I explained simply about laravel 10 jquery ajax post request example. This article will give you a simple example of laravel 10 ajax form submit example.
Ajax request is a basic requirement of any PHP project, we are always looking for without page refresh data should store in the database and it's possible only by jquery ajax request. the same thing if you need to write an ajax form and submit it in laravel 10 then I will help you how you can pass data with an ajax request and get on the controller.
In this example, we will create a "posts" table with a title and body column. we will list all post data and add create button there. when you click on create button we will open the model where you can create a new post using a jquery ajax request. so basically you can fire an ajax post request with a bootstrap model.
Step for Laravel Ajax POST Request Example
- Step 1: Install Laravel 10
- Step 2: Create Migration and Model
- Step 3: Create Controller
- Step 4: Create and Add Routes
- Step 5: Create Blade File
- Run Laravel App
so let's follow the below steps to do this example.
Step 1: Install Laravel 10
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Create Migration and Model
Here, we will create migration for "posts" table, let's run bellow command and update code.
php artisan make:migration create_posts_table
database/migrations/2022_02_17_133331_create_posts_table.php
<?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, run create new migration using laravel migration command as bellow:
php artisan migrate
Now we will create Post model by using 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 Controller
In this step, we will create a new PostController; in this file, we will add two method index() and store() for render view and create post with json response.
Let's create PostController by following command:
php artisan make:controller PostController
next, let's update the following code to Controller File.
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 and Add Routes
Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for render view and ajax post request.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(PostController::class)->group(function(){
Route::get('posts', 'index');
Route::post('posts', 'store')->name('posts.store');
});
Step 5: Create Blade File
At last step we need to create posts.blade.php file and in this file we will display all posts and write code for jquery ajax request. So copy bellow and put on that file.
resources/views/posts.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 Ajax Form Validation Example - ItSolutionStuff.com</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" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<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 bg-light mt-3">
<div class="card-header">
Laravel 10 Ajax Form Validation Example - ItSolutionStuff.com
</div>
<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">
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">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
/*------------------------------------------
--------------------------------------------
Form Submit Event
--------------------------------------------
--------------------------------------------*/
$('#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) => {
alert('Form submitted successfully');
location.reload();
},
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>
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/posts
Output:
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 10 Ajax Image Upload Example
- Laravel 10 React JS Auth Scaffolding Tutorial
- How to Create Migration in Laravel 10?
- Laravel 10 Database Seeder Example Tutorial
- Laravel 10 Mail | Laravel 10 Send Mail Tutorial
- Laravel 10 Eloquent Mutators and Accessors Example
- Laravel 10 Authentication using Jetstream Tutorial
- Laravel 10 Import Export Excel and CSV File Tutorial
- How to Send Email using Gmail in Laravel 10?
- Laravel 10 Generate PDF File using DomPDF Example
- Laravel 10 Multiple Image Upload Tutorial Example
- Laravel 10 File Upload Example Tutorial
- Laravel 10 Image Upload Example Tutorial
- Laravel 10 CRUD Application Example Tutorial