How to get array of objects sent by ajax in laravel

Member

by dedrick , in category: PHP Frameworks , 11 days ago

How to get array of objects sent by ajax in laravel

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 10 days ago

@dedrick 

To get an array of objects sent by AJAX in Laravel, you need to follow these steps:

  1. Create a route in your web.php file that listens for AJAX requests. For example:
1
Route::post('get-data', 'DataController@getData');


  1. Create a controller called DataController with a method called getData that handles the AJAX request:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
namespace AppHttpControllers;

use IlluminateHttpRequest;

class DataController extends Controller
{
    public function getData(Request $request)
    {
        $dataArray = $request->input('data');
        return response()->json($dataArray);
    }
}


  1. In your JavaScript file, make an AJAX request to the route you just created and pass the array of objects as data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var data = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Doe' }
];

$.ajax({
    type: 'POST',
    url: '/get-data',
    data: {
        data: data
    },
    success: function(response) {
        console.log(response);
    }
});


  1. When the AJAX request is successful, the controller will return the array of objects as a JSON response. You can then access this response in the success function of the AJAX request and do whatever you need with it.


That's it! You have successfully received an array of objects sent by AJAX in Laravel.