How to communicate with controller using ajax in laravel?

by giovanny.lueilwitz , in category: PHP Frameworks , a year ago

How to communicate with controller using ajax in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , a year 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: 'john@example.com',
    },
    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.

Related Threads:

How to validate a laravel form using jquery ajax?
How to fetch posts in laravel using ajax?
How to post array to php using ajax in laravel?
How to send an ajax request using jquery in laravel?
How to send data json via ajax to my controller in symfony?
How to create ajax in laravel?