How to get data from ajax call in laravel?

Member

by lily , in category: PHP Frameworks , 6 months ago

How to get data from ajax call in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 6 months ago

@lily 

To get data from an Ajax call in Laravel, you can follow these steps:

  1. Create a route in your web.php file: Route::post('/ajax-call', 'AjaxController@getData')->name('ajax-call');
  2. Create a new controller called AjaxController: php artisan make:controller AjaxController
  3. Open the AjaxController.php file and add the following method: all(); // Process the data or perform any desired actions // ... // Return a response return response()->json(['success' => true, 'data' => $data]); } }
  4. In your JavaScript file, make the Ajax call: $.ajax({ url: '{{ route('ajax-call') }}', type: 'POST', data: { // Pass any data you want key1: value1, key2: value2, // ... }, success: function(response) { // Handle the response from the server console.log(response); }, error: function(xhr) { // Handle any error that occurs during the Ajax call console.log(xhr.responseText); } });


When you make the Ajax call, Laravel will automatically route it to the getData method in the AjaxController. You can access the data sent from the Ajax call using the $request->all() method. You can then process the data, perform any desired actions, and return a response back to the client.