How to check if a post already exist on the page before refreshing and appending new posts
kindly guide me on this.
I'm building a forum page on my website with functionalities for posts/comments.
In my jquery file, i have a variable which holds the html wrapping the posts as below:
- var postHtml = '<div class="col-md-1"><img src="images/user.png" alt="image" width="50px" height="50px" background="#FC6806"></div><div class="col-md-11"><h5 style="color:#FC6806"><strong>'+user.name+'</strong></h5><h6 style="color:#FC6806">'+user.time+'</h6><h5 style="color:#0269C2"><strong>'+user.topic+'</strong></h5><p data- id="'+user.id+'">'+user.post+'</p></div><br/>';
Now i wrote a function of setInterval that refreshes the page every 5s. The effect of that is that each time it does, it appends all the posts as fetched from the database again...and that goes on and on and on.
What i want to incorporate is that each time the page refreshes, there should be a check of the posts id of the posts fetched and any one on the page already should not be appended, while new ones should be appended. I tried selecting the children and then check to see if any one has a data-id attribute of the post id currently on the page but i'm getting an error "Uncaught TypeError: $(...).children(...).exists is not a function".
Please find below my fetchpost function for fetching the posts from json file produced by sql.
- function fetchPosts(){
- var url = "fetch_posts.php";
- $.getJSON(url, function(data){
- $.each(data, function(i, user){
- if ($("#comment_thread").children("p[data-id='"+user.id+"']").exists()){
- var postHtml = '<div class="col-md-1"....(as shown in the first code above)
- $("#comment_thread").append(postHtml);
- }
- });
- });
- }
- fetchPosts();
-