How to make ajax work in laravel?

by elise_daugherty , in category: PHP Frameworks , 2 months ago

How to make ajax work in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 2 months ago

@elise_daugherty 

To make AJAX work in Laravel, you need to follow these steps:

  1. Include the jQuery library in your Laravel project by adding the following line in your layout file (usually in the head section):
1
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


  1. Create a route in your routes/web.php file to handle the AJAX request. For example:
1
Route::post('/ajaxRequest', 'AjaxController@ajaxRequest');


  1. Create a controller to handle the AJAX request. Run the following command to create a new controller:
1
php artisan make:controller AjaxController


Then, add the following code to your controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace AppHttpControllers;

use IlluminateHttpRequest;

class AjaxController extends Controller
{
    public function ajaxRequest(Request $request)
    {
        // Your logic here
    }
}


  1. Create a JavaScript file where you will send the AJAX request. For example, create a js/ajax.js file with the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$(document).ready(function() {
    $('#myForm').submit(function(e) {
        e.preventDefault();
        
        var formData = $(this).serialize();
        
        $.ajax({
            type: 'POST',
            url: '/ajaxRequest',
            data: formData,
            success: function(data) {
                console.log(data);
            }
        });
    });
});


  1. Include the JavaScript file in your layout file:
1
<script src="{{ asset('js/ajax.js') }}"></script>


  1. Add the CSRF token to your AJAX request by including the following line in your HTML layout file:
1
<meta name="csrf-token" content="{{ csrf_token() }}">


  1. Finally, make sure to add the CSRF token to your AJAX request headers:
1
2
3
4
5
6
7
$(document).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
});


By following these steps, you can make AJAX work in your Laravel project.