Laravel jquery ajax get method of data from database & print to view page

Viewed 24

I wanna fetch all posts from database by Ajax "GET" method & wanna show in a view page in Table row at Laravel project without reload/refresh page. but I'm facing some error's. My controller code

 //Controller
  public function getposts(){
      $posts = Post::orderByDesc('id')->simplePaginate('10');
      return response()->json([
        'posts'=>$posts,
      ]);
    }

jQuery code

    //JS
<script>

$(document).ready(function(){

  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });

 getPosts();
  function getPosts (){
    $.ajax({
      url: '/fetch-posts',
      type: 'GET',
              dataType: 'json',
              success: function(data) {
                console.log(data.posts);
      $('table tbody').html("");
      $.each(data.posts, function(key, item){
                  $('table tbody').append('<tr> \
                   <td>' + item.id + '</td> \
                   <td>' + item.text + '</td> \
                   <td>' + item.publish_type + '</td> \
                   </tr>');
              });

              }

            });

         }

});

</script>
1 Answers

you are missing the data element of the paginator. if you check your console.log(). you will find the data array element that provide all the array list.So modification below code of line

$.each(data.posts.data, function(key, item){
$('table tbody').append('<tr> \ <td>' + item.id + '</td> \ <td>' + item.text + '</td> \ <td>' + item.publish_type + '</td> \ </tr>');
});

Also edit you simple paginator to paginator so it will be

Post::orderBy('id', 'DESC')->Paginate('10');
Related