Comments in real time ajax

I plan to make this comment system where comments can be published and updated without refreshing the page (you can see it on youtube)

Posting comments is understandable (message to a php page from javascript and running a SQL query on the server side to import it, than returning a comment and selecting in html)

An update is a part that I do not understand. How can I refresh a page automatically at regular intervals and add comments? Isn't it a mess when multiple users try to comment at the same time?

I was wondering if anyone could recommend a good way (just like a word of advice) to achieve this and save me some time

+7
source share
4 answers

The most common way is to call setTimeout or setInterval in javascript to poll every 5-25 seconds. Basically, you keep the idea of ​​the last comment you received on the javascript side, then you call a function that sends this identifier to the remote server. If there are newer messages than this identifier, you send all of them back via XML or JSON (usually json is easier to handle on the javascript side, especially if you use a framework like jQuery).

+2
source

You can use the Long Survey. This is basically a method in which you open an Ajax connection and the server does not close until it receives any response to send. After receiving this response, the client requests a new connection and again waits for a response.

You can check out the tutorial: A simple long survey using JavaScript and jQuery .

+1
source

Another really good way would be to use a subscription / publish service.

I am using PubNub at the moment for notifications, comments, etc.

+1
source

I once used a simple technique (without a timer, without a general update) with the disadvantage that it only shows new comments, but does not edit or delete others made with existing displayed comments. Remember that updating the entire comment panel may not be feasible if you enable the "expand / collapse / view more" comments. My simple technique is to have (i) a hidden input element for storing the index / primary key of the last displayed comment (ii) several uniquely identified divs for storing existing displayed comments and ajax refresh or html dom manipulate only this div when actions are performed there is (iii) a div on it to hold the button for more comments, as a result of which the button will be displayed only if there are more comments to view.

Therefore, whenever a new comment is posted, the "comment panel with a large number of comments with a button" will be updated if you see the comments [X + (# last new comments from others) + (# your new comment)]. After clicking the button, it will display 3 more new comments along with the "Show more comments" button.

0
source

All Articles