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>