Search code examples
jqueryajaxlaravelcontroller

controller echo tabel with Ajax


How do I echo all records from the controller with a Ajax request? When I changed the code, I get only one name. So I made an array of the query. Unfortunately all Google answers didn't help.

My next step is also echo the score of the naam -> how can I echo naam and score in line?

Thanks for your help.

Controller code:

public function score(Request $request)
{
    $scores = DB::table('scores')->where('gameround_id', $gameround_id)->value('naam');
    $data = array();

 foreach ($scores as $score) {
   $data[] = $score->naam;
}

   return response()->json(['data'=> $data]); 
}

Ajax code:

   setInterval(function(){ 
   var gameround_id = '12';
   let _token   = $('meta[name="csrf-token"]').attr('content');
   $.ajax({
      type:'GET',
      url:"/ajaxRequestscore",
      data:{_token: _token, gameround_id: gameround_id},
      success:function(data){
        var html = '';
        data['data'].forEach(function(naam) {
            html += '<div>' + naam + '</div>'
        });
        $('#results').html(html);
      }
   });


  }, 1000);

Solution

  • First get data and return it as json: Controller:

    public function score(Request $request)
    {
        $data['scores'] = DB::table('scores')->where('gameround_id', $request->gameround_id)->get();
        
       return response()->json($data); 
    }
    

    View: Using JS and ajax send requests and then retrieve and append data to the view.

    <div id="scores"> </div>          
            
             <script>                 
                function mainTable() {
                   var gameroundID = '12';
                  $.ajax({
                        url: "{{url('/api/fetch-scores')}}",
                        type: "POST",
                        data: {
                        gameround_id: gameroundID,
                        _token: '{{csrf_token()}}'
                        },
                        dataType: 'json',                 
                        success: function (result) {
                        $.each(result.scores, function (key, value) {
                        $("#scores").append('<p> Naam: ' + value.naam + '</p><p>Score: ' + value.score + '</p>'); 
                       });
                     }
                  });
                }            
            </script>
    

    Update results every 5000 miliseconds:

    <script>
    setInterval(function(){
    $("#scores").html('');
    mainTable();
         }, 5000);
    </script>
    

    Route(web.php):

    use App\Http\Controllers\NaamController;
    Route::post('api/fetch-scores', [NaamController::class, 'score']);