Home » Jquery » javascript – how can i send json data from my controller to view?

javascript – how can i send json data from my controller to view?

Posted by: admin February 22, 2020 Leave a comment

Questions:
   public function getSectionsForClass(Request $request ,$id )
    {
        $section = Section::all()->where('clas_id',$id);
         return  response()->json($section);

    }

I need to send this json to my view in table like

@foreach($section as $sec)  
     {{$sec->section}}
      {{$sec->capacity}}
        {{$sec->teacher}}
      {{$sec->class}}

  @endforeach

This is my ajax code where i have send id and url

 <script type="text/javascript">
         $('#select_id').change(function(){
             // alert('hello');
             var cid = $(this).val();
             if(cid){
                 $.ajax({
                     dataType: "json",
                     url: 'section/index/'+cid,
                     //data: {'class': cid},
                     type:"GET",
                     success: function(response){
                         console.log ((response));

                     },error: (error) => {
                         console.log(JSON.stringify(error));
                   }
              });
             }
         });

     </script>

In Route

Route::get('admin/section/index/{id}','[email protected]');

Thanks in advance hope I will get my answer

How to&Answer:

As per the Laravel Documentation you can directly send the json response from your method

The json method will automatically set the Content-Type header to
application/json, as well as convert the given array to JSON using the
json_encode PHP function:

return response()->json([
    // You can pass your array values here
]);

And then you can create dynamic table from your ajax success at append that table in specific id for e.g

success: function(response){
         for (var key in response) {
          $('#here_table').append( '<tr><td>' + response[key] +  '</td></tr>' );
          }
 }

Laravel -> Http Responses -> Json Responses

Answer:

Currently, you are returning an instance of the Query Builder as a json response. You haven’t execute the query yet.

To get the results from your query you need to actually execute the query. Add get() at the end:

public function getSectionsForClass(Request $request ,$id )
{
    $section = Section::where('clas_id', $id)->get();
 //                                          ^^^^^^^
    return  response()->json($section);
}

Of course, this could be better managed in a paginated list in case you have lots of records, but you get the idea.