Laravel 11 AJAX request only showing the response data instead of executing the success function in AJAX. I have added all the code below.
Index.blade.php:
<table id="employeesTable" class="table table-hover datatable">
<thead>
<tr>
<th>ID</th>
<th>Image</th>
<th>Full Name</th>
<th>Email</th>
<th>Details</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Script:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script>
$(document).ready(function() {
fetchEmployees();
function fetchEmployees() {
$.ajax({
url: '/system/employee',
type: 'GET',
dataType: "json",
success: function(res) {
console.log(res.employees);
}
});
}
});
</script>
In Controller:
public function index()
{
$query = Employee::query();
$employees = $query->orderBy('created_at', 'desc')
->get();
return response()->json(["employees" => $employees]);
}
Response showing this –>
Response SS
I haven’t found any solution yet!
2
Answers
The solution is, basically we need two routes, one for the page view, another for the AJAX call.
Use the jquery .fail() function to read the error, but from what I see you need to add the url of your application either for the local environment or in production