skip to Main Content

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


  1. Chosen as BEST ANSWER

    The solution is, basically we need two routes, one for the page view, another for the AJAX call.


  2. 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

    url: BASE_URL + '/system/employee',
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search