Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Ajax Post Request Example

Last Updated on April 19, 2024 by

In Laravel 11, Ajax post requests allow users to submit a form to a controller or server and store it in your database without refreshing the page.

Let’s start creating a simple form and post the form using AJAX without page refresh:

Step 1 – Create a Form

Create a form in your Blade view file (resources/views/ajaxForm.blade.php):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 AJAX Post Requests Example - ItcodStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
    <div class="container mt-5">
        <form id="ajax-form">
            @csrf
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" id="name" name="name">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>
</html>

Step 2 – Implement AJAX Code

Use ajax to handle the form submission and include the CSRF token in the headers to prevent CSRF attacks:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function () {
        $('#ajax-form').submit(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "{{ route('submit-form') }}",
                data: $('#ajax-form').serialize(),
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    console.log(response);
                    // Handle success response
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                    // Handle error response
                }
            });
        });
    });
</script>

Step 3 – Create a Route

Define a route to handle the AJAX request in your web.php file, which is in routes folder:

use App\Http\Controllers\AjaxFormController;
use Illuminate\Support\Facades\Route;

Route::get('/ajax-form', [AjaxFormController::class, 'form']);

Route::get('/submit-form'', [AjaxFormController::class, 'submitForm'])->name('submit-form');

Step 4 – Create a Controller

Create a controller to handle the form submission logic. Use php artisan make:controller AjaxFormController to create it:

php artisan make:controller AjaxFormController

In your AjaxFormController.php file, create two methods to handle form submission logic:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxFormController extends Controller
{
    public function form(Request $request)
    {
          return view('ajax-form');
    }
    public function submitForm(Request $request)
    {
        // Process the form data (e.g., save to database)
        $name = $request->input('name');

        // Return a JSON response
        return response()->json(['message' => 'Form submitted successfully', 'name' => $name]);
    }
}

Step 5 – Run Application

Use php artisan serve command to start application server:

php artisan serve

Now open browser with http://127.0.0.1:8000/ajax-form.

Leave a Comment