Ajax post comment e.g. StackOverflow

My question is, what is the best way to make a comment system, for example, on StackOverflow, I mean, I send a request from my browser, and everyone will see this comment (or in another browser) without refreshing the page, for example, in chat.

My solution was to use setInterval , but I think there should be a different way

 $(document).ready(function() { get(); $('#send').click(function() { $.post('http://localhost/mvc.com/comment/post', { n_id: parseInt(newsId), user_id: $('#uid').val(), text: $('#content').val(), token: $('#token').val() }, function (ret) { if (ret.comm.err) { $('.f').empty().prepend('<li id=e><h3 style="color: red">ERROR</h3></li>'); return false; } get(); }); setInterval(get,3000); }); $('#content').keypress(function(e){ var key = e.which; var cnt=$(this).val().length; var max=100; var tot=parseInt(max-cnt); if(key >= 33 || key == 13 || key == 32) { if (parseInt(tot) <= 0) { e.preventDefault(); } } }); function get() { $.post('http://localhost/mvc.com/comment', {get: parseInt(newsId)}, function (ret) { $('.f').empty(); for (var key in ret.comm) { $('.f').append('<li class=c id=' + ret.comm[key].id + '><span>' + ret.comm[key].name + '</span><hr><br>' + ret.comm[key].text + '</li>'); } }); } 
+6
source share
2 answers

Although I saw that your above approach is used for real-time updates, but this is not the right way to do this.

You will need to use web sockets, which are de facto for real-time web applications.

Web sockets is a topic in itself, and I can continue, but here is a link to get you started with them: http://socketo.me

+4
source

You do not need setInterval. What you can do, the so-called long survey:

Javascript : you define an ajax function that calls itself:

 function poll(){ $.ajax({ type: "POST", url: url, data: data, success: function(msg){ update_poll(msg);//here you update your span, div, whatever what contains this comment }, dataType: "text", complete: function(){ poll();//here you call it again } }); } $(document).ready(function(){ poll();//call it just once }); 

PHP : you start a loop in one minute that checks every 3 seconds a new record in your database:

 if(isset($_POST['n_id'])){ $n_id = (int) $_POST['n_id']; $time = time(); while((time() - $time) < 60) { $last entry = get_last_entry($n_id); if($last entry){ echo $last_entry;//if found new entry, echo it out and break the loop break; } sleep(3);//wait 3 seconds } } 
+2
source

Source: https://habr.com/ru/post/985575/


All Articles