I have a homepage where there is a menu with some categories and below there are the latest posts:
<ul class="Categories__Menu">
@foreach($categories->take(6) as $category)
<li class="ative">
<a href="" name="category" id=""></a>
</li>
@endforeach
</ul>
<div class="row" id="posts">
@foreach($posts as $post)
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="" alt="Card image cap">
<h5 class="card-title"></h5>
<div class="card-footer d-flex justify-content-between align-items-center">
<a href="" class="btn btn-primary text-white">More</a>
</div>
</div>
</div>
@endforeach
</div>
I want that when each category is clicked to show only the posts of that category in the homepage, but in the same homepage, not in a specific category page.
So I have this Ajax:
$(function() {
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
$.ajax({
url: '/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
$('#posts').append("<p>"+postObj.name+"</p>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
});
And its working fine, but instead of show just this:
$('#posts').append("<p>"+postObj.name+"</p>");
I want to show the posts with the real html above like:
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="" alt="Card image cap">
<h5 class="card-title"></h5>
<div class="card-footer d-flex justify-content-between align-items-center">
<a href="" class="btn btn-primary text-white">More</a>
</div>
</div>
</div>
So Im using like this in ajax:
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
alert(category_id);
$.ajax({
url: '/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
//$('#posts').append("<p>"+postObj.name+"</p>");
$('#posts').append("<div class=\"col-12 col-sm-6 col-lg-4 col-xl-3 mb-4\">\n" +
" <div class=\"card box-shaddow\">\n" +
" <img class=\"card-img-top\" src=\"\" alt=\"Card image cap\">\n" +
" <h5 class=\"card-title h6 font-weight-bold text-heading-blue\"></h5>\n" +
" <div class=\"card-footer d-flex justify-content-between align-items-center\">\n" +
"\n" +
" <a href=\"\" class=\"btn btn-primary text-white\">More</a>\n" +
" </div>\n" +
" </div>\n" +
" </div>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
But it appears an error:
Use of undefined constant postObj - assumed 'postObj'
Do you know why?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire