1

What I'm trying to do is detect then collect new PHP array objects (sort of like an api) using ajax/jQuery methods.

{
    "posts": [
        {
            "id": "77",
            "post": ""Oh cool bro"",
            "time": "Mar 02, 2014"
        },
        {
            "id": "76",
            "post": "Ohh",
            "time": "Mar 02, 2014"
        },
        {
            "id": "75",
            "post": "Yupp",
            "time": "Mar 02, 2014"
        },
        {
            "id": "74",
            "post": "This is content",
            "time": "Mar 02, 2014"
        }
    ]
}

I'm trying to detect a new change in the array with ajax, if a user submits a new post, in real time the array is updated with a post with id 78. I want to be able to detect the addition and eppend only the new post. Additionally, I want the feed to be able to check for new posts every 5 seconds, and append the new posts instead of re-appending all of the posts. Almost exactly like the facebook feed ticker.

My jQuery/ajax code:

function getFeed() {
    $.ajax({
        type: "GET",
        url: "api.php",
        dataType: 'json',
        success: function(data) {
            var posts = data.posts
            $.each(posts, function(i) {
                $('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
            });
        } 
    });
}

4 Answers 4

2

Why not store the current posts IDs in a JavaScript array?

//An array that will contain the IDs of posts that have already
//been appended.
var displayedPosts = new Array();

//Function to get feed.
function getFeed() {
    $.ajax({
        type: "GET",
        url: "api.php",
        dataType: 'json',
        success: function(data) {
            var posts = data.posts
            $.each(posts, function(i) {
                //Make sure that this post hasn't already been added.
                if($.inArray(posts[i].id, displayedPosts) === -1){
                    //Store the ID of the post so that we don't add it again.
                    displayedPosts.push(posts[i].id);
                    //Append
                    $('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
                }
            });
        } 
    });
}

I must note that a better solution would involve using a timestamp parameter that is sent to api.php. i.e. Give me all posts that were posted after a particular timestamp (in this case, you'd be sending the timestamp of the last post as a parameter). That way, you're not repeatedly sending the same data to the client.

Sign up to request clarification or add additional context in comments.

Comments

2

The first time you call the api.php you could save in localStorage the last post of that user then the sucesive calls check if you have a value of last postId for that ignore all others inside your loop until you find the new postID.

 $.each(posts, function(i) {
               if(!localStorage["usernameX"]){
                  localStorage["username"] = posts[i].id;
                    $('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
                }else{
                   if(post[i].id >  localStorage["usernameX"]){
                        $('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
                    }
                }
                });

Comments

0

You should send last post id in ajax request and get towards records in ajax response, this would also helpful for performance, When Try this way

function getFeed() {
    var last_id  = $("#posts > div.post:last-child").length > 0 ? 
                      $("#posts > div.post:last-child").attr("id") : "0";
    $.ajax({
        type: "GET",
        url: "api.php",
        data : {"last_id" : }
        dataType: 'json',
        success: function(data) {
            var posts = data.posts
            $.each(posts, function(i) {
                $('#posts').append("<div class='post' id='" + posts[i].id + "'>" + "<div class='content'>" + posts[i].post + "</div>" + "<div class='meta'><div class='d'>" + posts[i].time + "</div> - <a href='/edit/" + posts[i].id +"'>Edit</a> - <a href='destroy.php?id=" + posts[i].id + "'>Delete</a></div></div>");
            });
        } 
    });
}

If last_id = 0 then the posts empty

And Use setInterval to call getFeed function every 5 second

setInterval(function() { getFeed(); }, 5000);

Comments

0

Add a variable in your JS to memorize the id of the last post displayed.

Create a PHP function that returns the id of the last post.

Then in your JS add somethinfg like this pseudo code:

setInterval(function() {
      // get the id of the last post
      // if it is  greater than the last post known by the JS, invoke getFeed()
}, 5000); // the time in milisecond before the next invocation of this function 

You must complete getFeed() to send the id of the last post you displayed, so the PHP returns only returns posts to be appended. Last, update the id of the last displayed post, according to the data returned by calling your API in getFeed().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.