How to get data from ajax request in laravel?

Member

by aubrey , in category: PHP General , 2 months ago

How to get data from ajax request in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 2 months ago

@aubrey 

To get data from an AJAX request in Laravel, you can use the request() method provided by Laravel.


Here's an example of how you can get data from an AJAX request in Laravel:

  1. In your JavaScript code, make an AJAX request using jQuery.ajax() or axios library. For example, using axios:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
axios.post('/your-url', {
    name: 'John',
    age: 30
})
.then(function (response) {
    console.log(response.data);
})
.catch(function (error) {
    console.log(error.response.data);
});


  1. In your Laravel controller, retrieve the data using the request() method:
1
2
3
4
5
6
7
8
9
public function yourControllerMethod(Request $request)
{
    $name = $request->input('name'); // Get the 'name' field from the request data
    $age = $request->input('age'); // Get the 'age' field from the request data
    
    // Do something with the data
    
    return response()->json(['success' => true]);
}


In the above example, the data sent from the AJAX request is received in the $request object. You can access the data using the input() method, and specify the field name as the parameter.


Make sure to include the Request class in your Laravel controller's file by adding use IlluminateHttpRequest; at the top of the file.


You can then perform any necessary operations with the received data and return a response using the response()->json() method.