How to call ajax in jquery in laravel?

Member

by denis , in category: PHP Frameworks , 5 months ago

How to call ajax in jquery in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 5 months ago

@denis 

You can call an AJAX request in jQuery in Laravel by using the $.ajax() function. Here's an example of how to make an AJAX request in jQuery in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
$(document).ready(function() {
    $('#submitBtn').click(function() {
        $.ajax({
            url: '/your-route-url',
            type: 'POST',
            dataType: 'json',
            data: {
                _token: '{{ csrf_token() }}',
                key1: 'value1',
                key2: 'value2'
            },
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {
                console.log(xhr.responseText);
            }
        });
    });
});


In this example, when the button with the id submitBtn is clicked, an AJAX request is made to the specified route URL using the POST method. The data sent in the request includes the csrf token and additional key-value pairs.


Make sure to replace '/your-route-url' with the actual route URL you want to call. Also, replace 'key1' and 'key2' with the actual data keys you want to send.


In the Laravel route file, don't forget to define the route like this:

1
Route::post('/your-route-url', [YourController::class, 'yourMethod']);


In your controller method, you can process the AJAX request and return the response as needed.


This is a basic example of how to call AJAX in jQuery in Laravel. You can further customize the AJAX call based on your specific requirements.