phpjsonlaravellaravel-10laravel-12

Json response not rendering to html table, only shows raw json data


I am returning json response from index method of my controller class.

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin\Services\Finish;

class FinishController extends Controller
{
    public function index()
    {
        $finishes = Finish::select('id','name')->where('status', 1)->orderBy('id','desc')->get();
        return response()->json(['finishes'=>$finishes]);
    }
}

My route function:

Route::get('admin_finish', [FinishController::class, 'index'])->name('admin_finish.index');

In my blade php file, I am trying to render this json response to html table. But it's only showing raw json data.

@extends('admin.index')
@section('admin_content')
    <section>
                    <table id="example2" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>S.No.</th>
                                <th>Finish Name</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="i_tbl_finish">
                        </tbody>
                    </table>
    </section>
@endsection

@section('js_scirpts')
    <script>
        $(document).ready(function() {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            fetchData();

            function fetchData() {
                    $.ajax({
                        type: "GET",
                        url:  "{{ route('admin_finish.index') }}",
                        dataType: 'json'
                        success: function(data) {
                            let rows = '';
                            $.each(data, function(key, finishes) {
                                rows += `
                                    <tr>
                                        <td>${finishes.id}</td>
                                        <td>${finishes.name}</td>
                                        <td>
                                            <button data-id="${finishes.id}" class="btn btn-primary btn-sm edit-post"><i class="fa fa-edit"></i></button>
                                            <button data-id="${finishes.id}" class="btn btn-danger btn-sm delete-post"><i class="fa fa-trash"></i></button>
                                        </td>
                                    </tr>
                                `;
                            });
                            $('#i_tbl_finish').html(rows);
                        },
                        error: function(error) {
                            console.log(error);
                        }
                    });
            }
        });
    </script>
@endsection

But I am getting only raw json data. It seems the ajax function is not working or may be issues with route. But I can not trace out the reason for this. Why is it so? Please see the attached image of my output.

output as raw json data


Solution

  • I think you have got the solution for your problem. Everything is clearly answered in the previous solutions.

    The issue is with your route and controller method. Create a separate method to fetch the data and define separate route for it and a separate route for your index page. For example,

    Route::get('admin_finish', [FinishController::class, 'index'])->name('admin_finish.index');
    // this route is for fetching the records
    Route::get('fetch-finish', [FinishController::class, 'fetchFinish'])->name('fetch-finish');
    

    For your controller method,

    public function index()
    {
         return view('admin.services.finish');
    }
    
    public function fetchFinish()
    {
        $finishes = Finish::select('id','name')->where('status', 1)->orderBy('id','desc')->get();
        return response()->json(['finishes'=>$finishes]);
    }
    

    For your ajax request,

                fetchData();
    
                function fetchData() {
                        $.ajax({
                            type: "GET",
                            url:  "{{ route('fetch-finish') }}",
                            dataType: 'json',
                            success: function(data) {
                                let rows = '';
                                $.each(data.finishes, function(key, item) {
    
                                    rows += `
                                        <tr>
                                            <td>${item.id}</td>
                                            <td>${item.name}</td>
                                            <td>
                                                <button data-id="${item.id}" class="btn btn-primary btn-sm edit-post"><i class="fa fa-edit"></i></button>
                                                <button data-id="${item.id}" class="btn btn-danger btn-sm delete-post"><i class="fa fa-trash"></i></button>
                                            </td>
                                        </tr>
                                    `;
                                });
                                $('#i_tbl_finish').html(rows);
                            },
                            error: function(error) {
                                console.log(error);
                            }
                        });
                }
    

    Note that in your fetchData function, comma is missing, make it `dataType: 'json', `.