I am trying to develop a website that shows a post automatically when it was posted by another user, or a user receives notification when a message has been sent to him, basically something that works like Facebook. Without needing to reload the page or hitting F5.
I have been working with Javascript and PHP for years and the only way to keep page updated as far as I know is by using AJAX requests continuously.
This is an example (Checking message from dataBase):
setInterval(function() {
$ajax({
url: "http://myweb.com/checkmessage.php",
type: "POST",
data: {value: userID},
dataType: "json",
success: function(result){
//If true do something and update message inbox
}
});
}, 500);
This basically sends requests every 0.5 seconds to my PHP file where I have access to my database and I check for new messages and return them. Thanks to this code I can get message notification in real-time without having to update my website.
But honestly, from performance perspective it's very bad practice to have hundreds AJAX requests sending every 0.5 seconds at once, it slows down the website.
That's why I am asking here if there is a better way to implement this, I have been checking Facebook and the way it was implemented pure mystery to me. I still don't know how do they do it, to have such massive updates on a page and just a few calls (You can check by yourself opening facebook waiting till it loads then open google developer tools, go to network and see it by your eyes!).