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!
2
Answers
Your logic is fine but few changes required.
You don’t have to pass full name of blade file and can use compact.
Controller:
Also confirm if you are sending content type as json in the ajax request.
I also had the same requirement but got some issues when I tried doing the following:
the problem I got was the page refreshing itself every Ajax request using Axios library as follows:
I solved the problem by attaching
application/json
on my request headers as follows: