How to communicate with controller using ajax in laravel?

by giovanny.lueilwitz , in category: PHP Frameworks , 6 months ago

How to communicate with controller using ajax in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 6 months ago

@giovanny.lueilwitz 

To communicate with a controller using AJAX in Laravel, you need to follow the following steps:

  1. Create a route for the controller method you want to communicate with via AJAX. In your routes/web.php file, add a route that points to the controller method. For example:
1
Route::post('/save-data', 'YourController@saveData')->name('save.data');


  1. Create the controller method in your controller file. In this method, you can handle the incoming AJAX request. For example:
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. In your frontend JavaScript code, use the $.ajax method (or any other AJAX library) to send a POST request to the URL defined in your route. For example:
 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.