Laravel 11 Ajax Request Example Tutorial | websolutioncode.com
Laravel 11 Ajax Request Example Tutorial | websolutioncode.com

Laravel 11 Ajax Request Example

Introduction:

In web development, Ajax (Asynchronous JavaScript and XML) is a powerful technique used to send and receive data asynchronously between the client and server without refreshing the entire page. Laravel, a popular PHP framework, provides robust support for handling Ajax requests seamlessly. In this tutorial, we’ll explore how to implement Ajax requests in Laravel 11 with practical examples.

Prerequisites:

Before diving into this tutorial, make sure you have the following prerequisites:

  • Basic understanding of PHP and Laravel framework
  • Laravel 11 installed on your local machine
  • A text editor or an IDE (Integrated Development Environment) for writing code

Setting Up a Laravel Project:

If you haven’t already set up a Laravel project, you can do so by running the following command in your terminal:

laravel new ajax-example

This command will create a new Laravel project named “ajax-example”.

Creating a Route:

Open the routes/web.php file in your Laravel project and define a route to handle the Ajax request:

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

Route::get('/ajax-request', [AjaxController::class, 'index']);
Route::post('/ajax-request', [AjaxController::class, 'store']);

Creating a Controller:

Now, let’s create a controller named AjaxController to handle our Ajax requests. Run the following command in your terminal:

php artisan make:controller AjaxController

This command will generate a new controller file named AjaxController.php under the app/Http/Controllers directory.

Writing Controller Logic:

Open the AjaxController.php file and define the index() and store() methods:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxController extends Controller
{
    public function index()
    {
        return view('ajax');
    }

    public function store(Request $request)
    {
        // Handle your Ajax request logic here
        return response()->json(['message' => 'Ajax request successful'], 200);
    }
}

Creating a View:

Now, let’s create a view file named ajax.blade.php under the resources/views directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax Request Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>Ajax Request Example</h1>
    <button id="ajaxButton">Send Ajax Request</button>

    <script>
        $(document).ready(function(){
            $('#ajaxButton').click(function(){
                $.ajax({
                    url: '/ajax-request',
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                    },
                    success: function(response){
                        alert(response.message);
                    },
                    error: function(xhr){
                        console.log(xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>

In this view file, we’ve included a button with the id ajaxButton. When this button is clicked, it triggers an Ajax request to the /ajax-request endpoint.

Handling Ajax Request in Laravel: Back in the AjaxController, the store() method is responsible for handling the Ajax request logic. You can perform any desired operations within this method and return a JSON response.

Testing:

Now, you can test the Ajax functionality by navigating to http://localhost:8000/ajax-request in your browser. Click the “Send Ajax Request” button, and you should see an alert with the message “Ajax request successful”.

Conclusion:

In this tutorial, we’ve covered how to implement Ajax requests in Laravel 11 effortlessly. By following the steps outlined above, you can seamlessly integrate Ajax functionality into your Laravel applications, enhancing user experience and interactivity. Experiment with different Ajax operations and explore further possibilities to leverage this powerful technique in your projects. Happy coding!

Leave a Reply