J
J
JackShcherbakov2018-02-17 17:00:42
PHP
JackShcherbakov, 2018-02-17 17:00:42

How to compose and answer a long survey?

Hello! I'm trying to make a long poll. That is, I want to make sure that the client does not send another request before the response from the server has passed. In my case, the answers should come once a minute. This is what the php code looks like:

<?php
$date = new DateTime();
$minutes = $date->format("i");
if($minutes%2 == 0){
  print "Сервер отправил запрос";
}
?>

Here is js:
function subscribe(url) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState != 4) return;

    if (this.status == 200) {
      console.log(this.responseText);
    } else {
       console.log(this);
    }

    subscribe(url);
  }
  xhr.open("GET", url, true);
  xhr.send();
}
subscribe("http://comet/php.php")

As a result, several dozen messages similar to this are fired several times per second into the console:
XHR finished loading: GET "http://comet/php.php"
Apparently, my server sends answers all the time. But how can I make the server send responses only if the number of current minutes is divisible by 2 without a remainder? How to do everything right? Or a js issue? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-02-17
@webinar

php is superfluous here, your whole task should be implemented in js. There are a lot of options, the most obvious is to put disabled on the button and by timeout, or maybe by the presence of a response from the server, or even hell knows what logic, remove disabled and make it possible to send again.
And your js just crap requests to the server as soon as it received a response from it. Actually a cycle.
This does not happen, the answers are not sent, this is the result of the request. No request, no response. You send requests from js without stopping, you need to stop it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question