Laravel AJAX Guide: Build Interactive Web Apps

laravel ajax

Introduction to Ajax in Laravel

When building web applications, speed and responsiveness are everything. No one likes waiting for a page to reload just to see updated content. That’s where Ajax in Laravel comes in. Ajax (short for Asynchronous JavaScript and XML) lets your website update specific sections without needing a full refresh, making everything feel faster and smoother.

Laravel, one of the most popular PHP frameworks, is built with modern web development in mind. It provides everything you need to handle Ajax requests efficiently, whether you’re submitting forms, fetching data, or updating the UI dynamically. With Laravel jQuery Ajax, you can send and receive data in the background, improving the overall user experience.

In this guide, we’ll cover everything you need to know about using Ajax with Laravel. You’ll learn how to set up Laravel for Ajax, process Ajax requests, and even build a complete Ajax Laravel example. By the end, you’ll have the knowledge to make your Laravel applications more dynamic and efficient.

Setting Up Laravel for Ajax Integration

Before we dive into handling Ajax requests, we need to set up Laravel properly. If you already have a Laravel project, you can skip the first step. Otherwise, let’s quickly get everything in place so we can start working with Laravel Ajax requests.

Install a New Laravel Project

First, make sure you have Composer installed. Then, create a new Laravel project by running:

composer create-project --prefer-dist laravel/laravel ajax-demo

Once the installation is complete, navigate into your project folder:

cd ajax-demo

Next, start the built-in development server:

php artisan serve

This should give you a local URL (usually http://127.0.0.1:8000) where your Laravel app is running.

If you are using an existing project, it’s a good idea to check which Laravel version you’re using. Different versions may have slight variations in routing, middleware, and request handling.

Configure the Database

Since we’ll be working with data, let’s set up the database connection. Open the .env file in your Laravel project and update the database settings:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=ajax_demo  
DB_USERNAME=root  
DB_PASSWORD=

Make sure you create a database named ajax_demo in your MySQL setup. You can do this using a tool like phpMyAdmin or running the following MySQL command:

CREATE DATABASE ajax_demo;

Once that’s done, run the migration command to generate Laravel’s default tables:

php artisan migrate

Set Up Routes and Controllers

Now, let’s create a controller to handle Ajax requests. Run the following command:

php artisan make:controller AjaxController

This will generate a new controller file inside app/Http/Controllers/AjaxController.php. Open the file and add a simple function to return a response:

public function getData() {  
    return response()->json(['message' => 'Ajax request successful!']);  
}

Next, define a route for this method in routes/web.php:

use App\Http\Controllers\AjaxController;

Route::get('/ajax-data', [AjaxController::class, 'getData']);

With this setup, we now have Laravel ready to handle Ajax requests. In the next section, we’ll look at how to send and process Ajax calls using JavaScript and jQuery.

Implementing Ajax Requests in Laravel

Now that Laravel is set up, let’s dive into how to send and process Ajax requests. We’ll create a simple form, submit it using Ajax, and handle the request in Laravel. This will make our application feel more dynamic by updating content without requiring a full page reload.

Creating a Form in the View

First, let’s create a basic form inside a Blade template. Open resources/views/welcome.blade.php and add the following:

<form id="ajax-form">
    <input type="text" id="name" name="name" placeholder="Enter your name">
    <button type="submit">Submit</button>
</form>

<div id="response-message"></div>

This form will allow users to enter their name and submit it via Ajax instead of a traditional form submission.

Writing the JavaScript Ajax Request

Now, let’s write the JavaScript to handle the Ajax submission. Add this inside a <script> tag at the bottom of the Blade file:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function(){
        $('#ajax-form').submit(function(event){
            event.preventDefault(); // Prevent form from submitting normally

            let name = $('#name').val();

            $.ajax({
                url: '/submit-form',
                type: 'POST',
                data: {
                    name: name,
                    _token: '{{ csrf_token() }}' // CSRF protection
                },
                success: function(response){
                    $('#response-message').text(response.message);
                },
                error: function(xhr){
                    $('#response-message').text('Error: ' + xhr.responseText);
                }
            });
        });
    });
</script>

This script does the following:

  • Prevents the form from submitting in the traditional way.
  • Sends the form data to Laravel using Ajax.
  • Handles the server response and updates the page dynamically.

Processing the Ajax Request in Laravel

Next, we need to handle this request in Laravel. Open routes/web.php and add a new route:

use Illuminate\Http\Request;

Route::post('/submit-form', function (Request $request) {
    $name = $request->input('name');
    return response()->json(['message' => 'Hello, ' . $name . '!']);
});

This route captures the name from the request and returns a JSON response with a greeting message.

Testing the Ajax Request

  1. Open your browser and go to your Laravel application (http://127.0.0.1:8000).
  2. Enter a name in the input field and click “Submit.”
  3. You should see a response message displayed below the form without the page reloading.

Congratulations! You’ve successfully made an Ajax request in Laravel. Next, we’ll take it a step further and build a complete Ajax CRUD Laravel example.

Practical Example: Ajax CRUD Operations in Laravel

Now that we’ve covered the basics of making Ajax requests in Laravel, let’s build a full Laravel CRUD example using Ajax. This will allow us to create, read, update, and delete records without refreshing the page.

We’ll create a simple project management system where users can add, view, edit, and delete projects using Ajax.

Step 1: Create the Migration and Model

First, let’s create a migration and model for our projects table:

php artisan make:model Project -m

Open the generated migration file inside database/migrations and update the up method:

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

Run the migration to create the table:

php artisan migrate

Now, open the Project.php model inside app/Models/ and define the fillable fields:

class Project extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'description'];
}

To quickly generate test data, you can use Laravel Faker to seed dummy data into your database. Faker helps create realistic sample records, making it easier to test Ajax requests without manually entering data.

To use Faker, first create a Laravel seeder for generating project entries.

Step 2: Set Up Routes and Controller

Now, create a controller to handle CRUD operations:

php artisan make:controller ProjectController

Open routes/web.php and define the routes for the CRUD operations:

use App\Http\Controllers\ProjectController;

Route::get('/projects', [ProjectController::class, 'index']);
Route::post('/projects', [ProjectController::class, 'store']);
Route::get('/projects/{id}', [ProjectController::class, 'edit']);
Route::put('/projects/{id}', [ProjectController::class, 'update']);
Route::delete('/projects/{id}', [ProjectController::class, 'destroy']);

Step 3: Implement the CRUD Logic in the Controller

Now, open app/Http/Controllers/ProjectController.php and add the following methods:

use App\Models\Project;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function index()
    {
        return response()->json(Project::all());
    }

    public function store(Request $request)
    {
        $project = Project::create($request->all());
        return response()->json($project);
    }

    public function edit($id)
    {
        return response()->json(Project::find($id));
    }

    public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project->update($request->all());
        return response()->json($project);
    }

    public function destroy($id)
    {
        Project::destroy($id);
        return response()->json(['message' => 'Project deleted']);
    }
}

Once your CRUD operations are set up, it’s a good idea to write unit tests in Laravel to verify that your Ajax requests work correctly. Laravel provides PHPUnit for testing, allowing you to simulate API calls and ensure everything functions as expected.

Step 4: Build the Frontend with Ajax

Now, let’s create a simple interface to manage projects. Open resources/views/welcome.blade.php and add the following:

<h2>Project Management</h2>

<form id="project-form">
    <input type="hidden" id="project-id">
    <input type="text" id="name" placeholder="Project Name">
    <textarea id="description" placeholder="Project Description"></textarea>
    <button type="submit">Save</button>
</form>

<ul id="project-list"></ul>

Next, add the JavaScript for handling Ajax operations:

<script>
    $(document).ready(function(){
        fetchProjects();

        $('#project-form').submit(function(event){
            event.preventDefault();
            let id = $('#project-id').val();
            let url = id ? '/projects/' + id : '/projects';
            let method = id ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                type: method,
                data: {
                    name: $('#name').val(),
                    description: $('#description').val(),
                    _token: '{{ csrf_token() }}'
                },
                success: function(response){
                    fetchProjects();
                    $('#project-form')[0].reset();
                    $('#project-id').val('');
                }
            });
        });

        function fetchProjects(){
            $.get('/projects', function(projects){
                let projectList = '';
                projects.forEach(project => {
                    projectList += `<li>
                        ${project.name} - ${project.description}
                        <button onclick="editProject(${project.id})">Edit</button>
                        <button onclick="deleteProject(${project.id})">Delete</button>
                    </li>`;
                });
                $('#project-list').html(projectList);
            });
        }

        window.editProject = function(id){
            $.get('/projects/' + id, function(project){
                $('#project-id').val(project.id);
                $('#name').val(project.name);
                $('#description').val(project.description);
            });
        }

        window.deleteProject = function(id){
            $.ajax({
                url: '/projects/' + id,
                type: 'DELETE',
                data: { _token: '{{ csrf_token() }}' },
                success: function(){
                    fetchProjects();
                }
            });
        }
    });
</script>

Step 5: Test the CRUD Application

  1. Open your browser and go to http://127.0.0.1:8000.
  2. Add a project using the form. It should appear in the list below.
  3. Click “Edit” to load a project’s data into the form.
  4. Click “Delete” to remove a project.

This setup allows us to create, read, update, and delete records without refreshing the page, making our Laravel app feel much more dynamic.

Next, we’ll go over some best practices to ensure smooth Laravel Ajax validation, CSRF protection, and debugging.

Best Practices for Using Ajax with Laravel

Now that we have a fully functional Ajax CRUD Laravel setup, let’s go over some best practices to ensure your application runs smoothly, securely, and efficiently.

1. Ensure CSRF Protection in Ajax Requests

Laravel includes CSRF protection by default, which helps prevent unauthorized requests. When sending an Ajax request, always include the CSRF token.

If you’re using jQuery, you can set up the token globally so you don’t have to include it in every request manually:

<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        }
    });
</script>

This ensures that every Ajax request includes the necessary CSRF token without you having to pass it in each request.

2. Organize JavaScript Code for Maintainability

Instead of embedding JavaScript directly inside Blade templates, move it to a separate file like public/js/ajax-scripts.js. Then, include it in your Blade file:

<script src="{{ asset('js/ajax-scripts.js') }}"></script>

This keeps your frontend clean and makes debugging much easier.

3. Use Laravel’s Validation for Ajax Requests

Instead of manually checking inputs in the controller, use Laravel’s built-in validation. Here’s an improved store method in ProjectController.php:

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|max:255',
        'description' => 'nullable|max:500'
    ]);

    $project = Project::create($request->all());
    return response()->json($project);
}

If validation fails, Laravel will return a JSON response with error messages, which you can handle in your Ajax script:

error: function(xhr) {
    let errors = xhr.responseJSON.errors;
    $.each(errors, function(key, value) {
        alert(value[0]); // Display the first validation error for each field
    });
}

4. Debugging Common Issues in Laravel Ajax Integration

If your Ajax requests aren’t working, here are some steps to troubleshoot:

  • Check the browser console (F12 → Console) for errors.
  • Inspect the network requests (F12 → Network → XHR) to see the request/response details.
  • Use Laravel’s debug tools like dd($request->all()); inside your controller to see what data is being received.
  • Check your route definitions to make sure they match the Ajax request URLs.
  • Enable Laravel Debug Mode in .env to get more detailed error messages: APP_DEBUG=true

5. Optimize Ajax Requests for Performance

  • Use caching to store frequently used data and reduce unnecessary queries.
  • Limit the response data by selecting only the fields you need (Project::select('id', 'name')->get();).
  • Batch requests instead of sending multiple Ajax calls in a short period.

FAQs

How do I send an Ajax request in Laravel?

You can use jQuery’s $.ajax() or the Fetch API to send requests. Make sure to include the CSRF token in the headers and define routes in Laravel to handle the request.

Why is my Ajax request not working in Laravel?

Check the browser console for errors, ensure the correct route and method are used, and confirm the CSRF token is included. Also, inspect the Laravel logs for server-side issues.

How do I return a JSON response in Laravel Ajax?

Use Laravel’s response()->json() method inside your controller to send JSON data back to the frontend, which can then be processed using JavaScript.

How do I validate Ajax form submissions in Laravel?

Use Laravel’s built-in validation in the controller and return validation errors as a JSON response. Then, handle the errors in JavaScript to show feedback to users.

How do I implement Ajax CRUD operations in Laravel?

Set up routes, create a controller, define methods for create, read, update, and delete operations, and use jQuery Ajax to send and receive data dynamically.

How can I improve Ajax performance in Laravel?

Optimize database queries, use caching, minimize response data, and batch requests when possible to reduce the load on the server and improve speed.

Final Thoughts

Using Ajax in Laravel makes web applications feel fast and responsive. Whether you’re handling form submissions, fetching data dynamically, or building a full CRUD application, Ajax simplifies the user experience.

By following best practices—like securing requests with CSRF protection, validating input, and optimizing performance—you’ll ensure that your Laravel applications remain secure, maintainable, and scalable.

Now it’s your turn! Try implementing Ajax in your Laravel projects and see how much smoother your applications feel. If you run into issues, check Laravel’s documentation or debug using the tips above.

Photo of author
As Editor in Chief of HeatWare.net, Sood draws on over 20 years in Software Engineering to offer helpful tutorials and tips for MySQL, PostgreSQL, PHP, and everyday OS issues. Backed by hands-on work and real code examples, Sood breaks down Windows, macOS, and Linux so both beginners and power-users can learn valuable insights. For questions or feedback, he can be reached at sood@heatware.net.