-1

So I have a script that uses basic polling to show the total amount of records in the database in real time

so nothing complicated so can any one give me an example of my code in a long polling structure. The reason why I ask this question because all the articles on google

search gives me examples in jQuery I cant seem to find a plain JavaScript example that makes sense in my situation. This is a .gif screenshot of my code in action so you guys know what I mean in detail.

.gif-example

This is my basic polling example code that I need to convert or change into long polling.

index.php

<style>
    #label{
    margin: 0;
    color: red;
    font-weight: bold;
    }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded',function(){

    /**********************************************************************
    Check for a new record amount in the data base
    **********************************************************************/

    function checkForNewRecords(){

    var xhr= new XMLHttpRequest();

    xhr.onreadystatechange= function(){

        if(xhr.readyState == 4){
        document.querySelector('#output').innerHTML= xhr.responseText;

        }
      }

    xhr.open('POST','check-for-new-records.php');
    xhr.send();  

    }

    setInterval(function(){checkForNewRecords()},1000);

    });
    </script>

    <p id='label'>Total records in the database in real time in basic polling</p>

    <div id='output'></div>

check-for-new-records.php

<?php

    $db_servername= 'localhost';
    $db_username='jd';
    $db_password= '1234';
    $db_name= 'test';

    $db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);

    $db_query= "SELECT COUNT(id) AS id FROM example";

    $db_result= $db_connect->query($db_query);
    $db_row= $db_result->fetch_object();

    $total_records= $db_row->id;

    ?>

    <style>
    #total-records{
    margin-top: 0;
    }
    </style>

    <p id='total-records'><?php echo $total_records; ?></p>

So how would you guys convert this into long polling and please don't suggest other methods or don't provide an answer that is not helpful i'm only interested in what i'm asking for and i'm pretty sure others are also interested in a plain JavaScript version as well and the reason why I say this is because I

been asking about this topic online for a long time and nobody seems interested in answering this or perhaps they think its too hard to answer this if so why is there so many jQuery examples about this topic and not based on plain JavaScript and not everyone likes to use libraries. I'm just saying I been unsatisfied about the unhelpful answers I been getting from this topic that is based on plain JavaScript, just a heads up.

  • fwiw, your final run on sentence is likely to get downvotes. Just a heads up. – Taplar Dec 31 '18 at 20:37
  • 1
    Hope this help, I didn't want to code the solution because it's December 31, but the explanation here is pretty clear https://developer.hyvor.com/php/ajax-long-polling – Polak Dec 31 '18 at 20:52
  • You should never use `setInterval` use `setTimeout` instead. If you use `setTimeout` then polling and long polling only differ where the delay happens. For polling the server will respond immediatly (even if no change happened) and the client will wait _n_ seconds to send the next request. For long polling the server will wait with the respond until new data is available (or a timeout occurs) and the client will immediately send a new request when it gets a response. – t.niese Dec 31 '18 at 21:11
  • Thanks every one for your response but why is this question so complicated to most people but yet if some one asked this how can this be done in jQuery an answer is given fast is JavaScript to complicated for most people now days? I just don't get it sorry guys I been frustrated with the lack of info about doing this with plain JavaScript i'm just saying and thank you Polack for you're link but I already tried that link out and I could not get it to work with my example I learned best by my example but if you guys don't know how it's ok I just got to keep asking online since I failed a lot. –  Dec 31 '18 at 21:23
  • And asking the nearly identical question [Converting this from basic polling to long polling](https://stackoverflow.com/questions/53965771/converting-this-from-basic-polling-to-long-polling) without telling what was missing in those answers, is a really bad manner. – t.niese Dec 31 '18 at 21:49

1 Answers1

0

You should never use setInterval use setTimeout instead.

If you use setTimeout then basic difference for polling and long polling is only where the delay happens. For polling the server will respond immediatly (even if no change happened) and the client will wait n seconds to send the next request. For long polling the server will wait with the respond until new data is available (or a timeout occurs) and the client will immediately send a new request when it gets a response.

There is absolutely no different in implementing it with XMLHttpRequest, fetch or jQuery, the only difference client side is the delay for the next request.

Polling:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 1000); // polling has the delay on the client
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

Long-Polling:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 0);
      // long-polling has the delay on the server 
      // the client initiates a new request immediatly after receiving the response.
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

On the server side, on the other hand, you usually have to change a couple of things to make long polling work efficiently.

The important differences between polling and long polling that target optimizations, in how to tell the server when to send update informations, but thats completely independent form the method you use to request the data.

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • Thanks for your response t.niese but I see no difference between your basic polling and the long polling example you are giving. All I see is the time is different well to answer your other comments to me I was not being rude I just realize I was not getting any where from that post because as soon as I saw that people stopped viewing it and they were not giving me helpful answers then I was trying to close that post but it did not let me but if you don't know how to do this in the server side as well it's ok if you don't know how i'm just glad some one reached out well I hope I can solve this –  Dec 31 '18 at 22:13
  • @fsofb That's what I said in the answer. It's because there is **no** other difference between long polling and polling on the client side. Polling means, the server does not support a delay (holding the response until an update is there) so the client is responsible for the task of delaying the next request to reduce network load. For long polling the server is able to delays the response until new/updated data is available so the server is responsible to delay the response and to control the network load. So on the client side the difference is effectively just that value for the timeout. – t.niese Dec 31 '18 at 22:20
  • @fsofb to be clear there are two parts in long polling, your question is about the client side part how to do that with JavaScript and not with jQuery. That's what I answered, and it is not different to how you do that with jQuery. The server side part is a different topic, and completely unrelated to the language and/or library used on the requesting side. So if you want to know how to do the server side part then you need to ask about that. – t.niese Dec 31 '18 at 22:30