jQuery AJAX allows users to get data from the controller or display it on the view without reloading the web page.
Let’s start to get and pass data from controller to view using ajax laravel 11:
Step 1: Create a View
Create showData.blade.php
view file in the resources/views
directory and send ajax get requests to controller, and then display the data in view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>how to pass data from view to controller using ajax laravel - itcodStuff.com</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h1 class="mb-4">User Data</h1>
<div id="user-data">
<!-- Data will be loaded here -->
</div>
</div>
</body>
</html>
Step 2: Send Ajax Request to Controller
Use jQuery ajax function in view file that handle ajax send requests to controller on view:
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: '/get-data',
type: 'GET',
success: function(response){
var data = response;
var userData = '<ul class="list-group">' +
'<li class="list-group-item">Name: ' + data.name + '</li>' +
'<li class="list-group-item">Age: ' + data.age + '</li>' +
'<li class="list-group-item">Email: ' + data.email + '</li>' +
'</ul>';
$('#user-data').html(userData);
}
});
});
</script>
Step 3: Define Route
Create route in web.php file that handle ajax requests:
use App\Http\Controllers\DataController;
Route::get('/get-data', [DataController::class, 'getData']);
Step 4: Create Controller
Create a controller file that allows users to pass JSON data from the controller to the view:
php artisan make:controller DataController
Create method in controller file that handles ajax requests and sends data back to view:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DataController extends Controller
{
public function getData()
{
$data = [
'name' => 'John Doe',
'age' => 30,
'email' => '[email protected]'
];
return response()->json($data);
}
}
Step 5: Test Application
Now, you can run your Laravel application using the following command:
php artisan serve
Hit http://localhost:8000/show-data
url in your browser to test send data from the controller and displayed on the page using Ajax.