Home > Mobile >  How do I Render a view with Ajax in Laravel 9
How do I Render a view with Ajax in Laravel 9

Time:10-06

I want to render a view without refreshing my page, so I use Ajax and render the view. It look likes my $scores won't work, should it be an array or not? I've read something about it should be json data?

Controller:

$scores = DB::table('scores')->select('teamname', 'score')->get();
$table_view = view('score_table.blade.php', ['scores'=>$scores])->render();
return response()->json(['succes' => true, 'table_view' => $table_view]);

View score_table.blade.php

<table>
    <tr>
        <th> Teamname </th>
        <th> Score </th>
    </tr>
    @foreach($scores as $score)
        <tr>
            <td> {{ $score->teamname }} </td>
            <td> {{ $score->score }} </td>
        </tr>
    @endforeach
</table>

Ajax function

 success:function(data){
            
            $('#scoreresult').html(data.table_view);

         }

I was pretty sure that it would work, but it didn't :(. Who can help me with a solution? Many thanks!

CodePudding user response:

Your logic is fine but few changes required.

You don't have to pass full name of blade file and can use compact.

Controller:

$scores = DB::table('scores')->select('teamname', 'score')->get();
$table_view = view('score_table', compact('scores'))->render();
return response()->json(['succes' => true, 'table_view' => $table_view]);

Also confirm if you are sending content type as json in the ajax request.

dataType: "json",
success:function(data){
      $('#scoreresult').html(data.table_view);
}
  • Related