How to send an ajax request using jquery in laravel?

by mallory_cormier , in category: PHP Frameworks , a month ago

How to send an ajax request using jquery in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , a month ago

@mallory_cormier 

To send an AJAX request using jQuery in Laravel, you can follow these steps:

  1. First, include the jQuery library in your Laravel application. You can include it by adding the following line in the head section of your HTML file:
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


  1. Next, create a route in your Laravel application to handle the AJAX request. You can define the route in your web.php file.
1
Route::post('/ajax-request', 'AjaxController@handleAjaxRequest')->name('ajax.request');


  1. Create a controller called AjaxController that will handle the AJAX request. You can create the controller by running the following command in your terminal:
1
php artisan make:controller AjaxController


  1. In the AjaxController, create a method called handleAjaxRequest that will process the AJAX request.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
namespace AppHttpControllers;

use IlluminateHttpRequest;

class AjaxController extends Controller
{
    public function handleAjaxRequest(Request $request)
    {
        // Process the AJAX request here
        return response()->json(['message' => 'AJAX request sent successfully']);
    }
}


  1. Finally, in your JavaScript file, send an AJAX request to the route you defined earlier using the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$.ajax({
    url: "{{ route('ajax.request') }}",
    type: "POST",
    data: {
        // Add any data you want to send in the request
    },
    success: function (response) {
        console.log(response);
    },
    error: function (xhr, status, error) {
        console.error(error);
    }
});


That's it! You have successfully sent an AJAX request using jQuery in Laravel.