DEV Community

Sanjay Kumar
Sanjay Kumar

Posted on

Laravel 10 How To Setup Ajax Request Tutorial

In the ever-changing web development ecosystem, Ajax (Asynchronous JavaScript and XML) has emerged as a vital technology for constructing interactive and responsive web applications.

Setting up Ajax requests in Laravel 10 facilitates communication between your frontend and backend, allowing for real-time updates and improved user experiences without the need for full page reloads.

We will walk you through the process of configuring Ajax requests in Laravel 10 in this tutorial. We'll look at how to utilise JavaScript and jQuery to send asynchronous queries to your backend, provide data, and handle real-time responses.

Let's get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Settings Up Controller

Open project into terminal and type this command to create controller file.

$ php artisan make:controller AjaxController

This command will create a file i.e AjaxController.php inside /app/Http/Controllers folder.

Open this file and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxController extends Controller
{
    public function myPost()
    {
        return view('my-post');
    }

    public function submitPost(Request $request)
    {
        // We are collecting all data submitting via Ajax
        $input = $request->all();

        // Sending json response to client
        return response()->json([
            "status" => true,
            "data" => $input
        ]);
    }
}

Enter fullscreen mode Exit fullscreen mode

Inside this above code, you have added a method which is processing ajax data. You can even use this data to insert into database table.

Next,

Create Blade Template

Go inside /resources/views folder. Create a file called my-post.blade.php

Open up the file and write this complete code into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Laravel 10 How To Setup Ajax Request Tutorial - Online Web Tutor</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <style>
    #frm-create-post label.error {
        color: red;
    }
    </style>
</head>

<body>

    <div class="container" style="margin-top: 50px;">
        <h4 style="text-align: center;">Laravel 10 How To Setup Ajax Request Tutorial - Online Web Tutor</h4>
        <form action="javascript:void(0)" id="frm-create-post" method="post">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" required id="name" name="name" placeholder="Enter name">
            </div>
            <div class="form-group">
                <label for="description">Description:</label>
                <textarea class="form-control" id="description" required name="description"
                    placeholder="Enter description"></textarea>
            </div>
            <div class="form-group">
                <label for="status">Status:</label>
                <select class="form-control" id="status" name="status">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>

            <button type="submit" class="btn btn-primary" id="submit-post">Submit</button>
        </form>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>

    <script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $("#frm-create-post").validate({

            submitHandler: function() {

                var name = $("#name").val();
                var description = $("#description").val();
                var status = $("#status").val();

                // processing ajax request    
                $.ajax({
                    url: "{{ route('postSubmit') }}",
                    type: 'POST',
                    dataType: "json",
                    data: {
                        name: name,
                        description: description,
                        status: status
                    },
                    success: function(data) {
                        // log response into console
                        console.log(data);
                    }
                });
            }
        });
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Add Route

Open web.php file from /routes folder. Add these routes into it.

//...
use App\Http\Controllers\AjaxController;

Route::get('add-post', [AjaxController::class, 'myPost']);
Route::post('submit-post', [AjaxController::class, 'submitPost'])->name('postSubmit');
Enter fullscreen mode Exit fullscreen mode

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL: http://localhost:8000/add-post

Submitting Data and getting response to Console

Ajax request setup in Laravel 10

We hope this article helped you to learn about Laravel 10 How To Setup Ajax Request Tutorial in a very detailed way.

Top comments (0)