How to Create Ajax Request In Laravel 9 ?

Hello All, Today now in this tutorial i will focused on the laravel 9 ajax request example. So here I’m going to show you how we can use ajax in our laravel 9. Here i will show you step by step also with explain laravel 9 jquery ajax post request example. So here step by step explains of laravel 9 ajax form submit example.

We know that ajax request is a basic needed of any kind of php project. We are always looking for the without page refresh data should store in our database and also it’s possible only the by jquery ajax request. So same thing if we are need to write an ajax form submit in laravel 9 application then here I will help you about how you can pass the data with an ajax request and also get on the controller.

Now in this example, i will be create a “posts” table also with a title and body column. Here i will be also list all posts data and then add create button there. when we will click on the create button then it will open the model where we can create a new post by using a jquery ajax request. So it is basically we can fire an ajax post request also with a bootstrap model.

so let’s start and follow the below step to do this example.

Step 1: Install Laravel 9

This is first step, this step is not needed if you have already install laravel 9 project; however, if you don’t have then need to created the laravel app, then you may go command line and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Migration and Model

Here, i will create the migration for the “posts” table, so let’s run the bellow command and the update code.

php artisan make:migration create_posts_table

database/migrations/2022_03_15_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()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Next, need to run create new migration by using laravel migration command as bellow:

php artisan migrate

Now i will create Post model by 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 Controller

Now in this step, i will create a new controller as PostController; then in this file, i will add two method index() and store() for the render view and create the post with json response.

Let’s start and create PostController by using the following command:

php artisan make:controller PostController

next, let’s update the following code to the 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;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $posts = Post::get();
  
        return view('posts', compact('posts'));
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'body' => 'required',
        ]);
  
        if ($validator->fails()) {
            return response()->json([
                        'error' => $validator->errors()->all()
                    ]);
        }
       
        Post::create([
            'title' => $request->title,
            'body' => $request->body,
        ]);
  
        return response()->json(['success' => 'Post created successfully.']);
    }
}
Step 4: Create and Add Routes

Furthermore, now need to open routes/web.php file and then add the routes to manage GET and POST requests for the 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

Now at the last step we have to create the posts.blade.php file and then in this file i will display all posts and also write code for jquery ajax request. So just need to copy the bellow code and put on that file.

resources/views/posts.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Create  Ajax Request In Laravel 9 ? - CodingsPoint.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">
           How to Create  Ajax Request In Laravel 9 ? - CodingsPoint.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 >
  
            <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="name" class="form-control" placeholder="Name" required="">
            </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">
      
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  
    $(".btn-submit").click(function(e){
    
        e.preventDefault();
     
        var title = $("#titleID").val();
        var body = $("#bodyID").val();
     
        $.ajax({
           type:'POST',
           url:"{{ route('posts.store') }}",
           data:{title:title, body:body},
           success:function(data){
                if($.isEmptyObject(data.error)){
                    alert(data.success);
                    location.reload();
                }else{
                    printErrorMsg(data.error);
                }
           }
        });
    
    });
  
    function printErrorMsg (msg) {
        $(".print-error-msg").find("ul").html('');
        $(".print-error-msg").css('display','block');
        $.each( msg, function( key, value ) {
            $(".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

Read Also: How To Implement Laravel 9 form validation ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →