Q:

Laravel & Ajax - foreach json object & dealing with duplicates

im trying to make a simple notification system using Ajax and Jquery. 
What i've done so far is:

Created a php file from which i load latest post and its title
Return json from php file mentioned above containing latest post and it's title
Created ajax post request that fetches the latest post from the json and its name using the data parameter in success: function(data)
Set an interval that repeats ajax call every 5 seconds
prepend the latest post title in notification div

Problems i have are:

If i set the interval on 1 minute and create 2 or more new posts it will only give the newer one (obviously since i called ->first() from my ->latest(), otherwise it wont load anything)
As i mentioned before, my setInterval is set to 5 seconds, and then it loads the latest post, and it does that every 5 seconds so i have an identical new post every 5 seconds until the newer one comes, i tried fixing it by prepending only higher id than the last one, but im not sure how reliable is that

Scripts:
Notification.php:
$post = Post::latest()->first();
$post_title = $post->title;

return response->json(array('post' => $post, 'post_title' => $post));

View with AJAX:
function getnewnotif()
{
$.ajax({
type:'POST',
url: url_to_notification.php,
success: function(data){
$('#notif').prepend(data.post_title);
}
});
}

setInterval(getnewnotif(), 5000);

A:

You were definitely on the right track with IDs, but more reliable is likely the creation (or updated) date.
In its simplest form, when you send your request for more posts, send a "last request date" parameter. On the server, use that to only grab posts that have been created (or modified - not sure which you want) after that date. On the client, where you make the ajax calls, you'll need to remember the last date you requested data from the server, so you can use it in your next ajax call.
But that will not work perfectly well when multiple timezones are involved.
A sturdier approach is for the server to tell you it's local time. So you send your first ajax call, and along with the list of posts, the server also returns the time it sent you the data. Your javascript grabs that date, and on your next ajax call, you send that to the server. It can then return to you just new posts that were created after that date. Since it's always server date vs server date, timezones don't matter here.
Hope this helps!

