How to get a value from ajax call in laravel?

by muriel.schmidt , in category: PHP Frameworks , a year ago

How to get a value from ajax call in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a year ago

@muriel.schmidt 

To get a value from an Ajax call in Laravel, you can use the request() function in your controller. Here's an example:

  1. Create a route in your web.php file:
1
Route::post('/ajax-call', 'YourController@ajaxCall');


  1. In your controller, create a method to handle the Ajax call:
1
2
3
4
5
6
7
public function ajaxCall(Request $request)
{
    $value = $request->input('value'); // replace 'value' with the name of your input field in your Ajax call
    // process the value or do whatever you want with it

    return response()->json(['message' => 'Success!']); // return a response if needed
}


  1. In your JavaScript file, make an Ajax call:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$.ajax({
    url: '/ajax-call',
    method: 'POST',
    data: {
        value: 'your value' // replace 'your value' with the actual value you want to send
    },
    success: function(response) {
        // process the success response
    },
    error: function(xhr) {
        // handle the error response
    }
});


In the ajaxCall method of your controller, you can access the value sent from the Ajax call using $request->input('value').