Milind Daraniya

How to Call Laravel Route in jQuery and JavaScript

Published September 21st, 2023 13 min read

Laravel, a popular PHP framework, provides a powerful routing system that makes it easy to define and manage your application's routes. You can use route names to reference routes throughout your application, even when making AJAX requests using jQuery or JavaScript. In this tutorial, we'll guide you through the process of calling a Laravel route using its name in jQuery and JavaScript.

Step 1: Define Your Laravel Routes

In your Laravel application, define the routes you want to call using route names. For example, open your routes/web.php file and define a named route:

Route::get('/example', 'ExampleController@index')->name('example.index');

Step 2: Include jQuery or JavaScript

In your HTML or Blade template file, include the jQuery library or use native JavaScript. Make sure to include the necessary scripts before your custom script that calls the route.

Step 3: Call the Laravel Route

Now, you can use the route name to call the Laravel route using AJAX requests.

Using jQuery:

<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Your custom script -->
<script>
$(document).ready(function() {
    $('#callRouteButton').click(function() {
        $.ajax({
            type: 'GET',
            url: '{{ route("example.index") }}', // Use the route name
            success: function(response) {
                // Handle the response
            },
            error: function(error) {
                // Handle errors
            }
        });
    });
});
</script>

Using JavaScript (Native):

<!-- Your custom script -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const callRouteButton = document.getElementById('callRouteButton');

    callRouteButton.addEventListener('click', function() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '{{ route("example.index") }}'); // Use the route name

        xhr.onload = function() {
            if (xhr.status === 200) {
                const response = xhr.responseText;
                // Handle the response
            } else {
                // Handle errors
            }
        };

        xhr.onerror = function() {
            // Handle errors
        };

        xhr.send();
    });
});
</script>

Step 4: Create the Controller Method

Finally, make sure you have the corresponding controller method (ExampleController@index in this case) to handle the route request and return the desired response.