@giovanny.lueilwitz
To communicate with a controller using AJAX in Laravel, you need to follow the following steps:
1
|
Route::post('/save-data', 'YourController@saveData')->name('save.data');
|
1 2 3 4 5 6 7 8 |
public function saveData(Request $request)
{
// Handle the AJAX request
// Perform necessary validation or data processing
// Return a JSON response
return response()->json(['success' => true, 'message' => 'Data saved successfully']);
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$.ajax({
url: '/save-data',
method: 'POST',
data: {
// Include any data you want to send to the controller method
name: 'John Doe',
email: '[email protected]',
},
success: function(response) {
// Handle the response from the controller method
console.log(response.message);
},
error: function(xhr) {
// Handle any errors that occur during the AJAX request
console.log('Error: ' + xhr.status);
}
});
|
In this example, the saveData method in the YourController will be called when the AJAX request is made to the /save-data URL. The method can handle the request, perform necessary validation or data processing, and return a JSON response.