Polling! What am I doing wrong

I have the following function in order to check if there are any new reactios to a certain blogpost:

$(function() {
    var lastChecked = '';
    function addResp(type, resp) {
            "<div class='resp "+ type +"'>"+ resp +"</div>"
    function waitForResp() {
            type: "GET",
            url: "/responses?since="+lastChecked,
            async: true,
            cache: false,
            success: function(data) {
                if (data) {
                    lastChecked = data.lastChecked;
                    data.resp.forEach(function(item) {
                        addResp("new", item.name);
						addResp("new", item.response);
				setTimeout(waitForResp, 5000);

But for some reason it keeps giving me the same reactions over and over again, in other words every 5 seconds the function is appending the same messages again. What am I doing wrong?

Is lastChecked returned from the server correctly? Does the /responses endpoint honor the since parameter?

As far as I can see those are the only two things that can go wrong.

1 Like

@rpkamp. Hi Scallio. :How do I check that?

Just for your information these are the model and controller functions:

	public function get_responses($response_date=false)
		$sql	=	"SELECT *
		               FROM `post_responses`";
		$params = array();
		if ($response_date)
			$sql	.=	" WHERE `response_date` > :response_date";
			$params[':response_date'] = $response_date;	
		$stmt = $this->pdo->prepare($sql . " ORDER BY `post_id` DESC");
		return $stmt->fetchAll(PDO::FETCH_ASSOC);	


    public function responsesAction()
        if (empty($_GET['since']))
            $responses    =    $this->blog->get_responses();
            $responses    =    $this->blog->get_responses($_GET['since']);    
        $data    =    $responses;
        header('Content-Type: application/json');
        echo json_encode(array(
            'resp'        	=>    $data,
            'lastChecked'   =>     time()

Maybe I should take a different approach? What do you think?

It looks like you’re comparing the date of the last request with the dates when the responses were created… and since that latter date won’t change, you get the same responses over and over again. Instead, you might store the ID of the latest response from the last request in a session variable (or just send it back to the server as a request parameter), and subsequently only query for responses with an ID greater than that.

1 Like

@m3g4p0p. Thank you very much for the reply. This is driving me insane :banghead: . I am looking for hours now. Everywhereelse I see people using timestamp but I can’t get it to work in my situation. How would it work with what you suggest, can you please give me an example

Can you post how your post_responses looks like, i.e., the output of SHOW CREATE TABLE post_responses?

@rpkamp. This is how the table looks like:

CREATE TABLE IF NOT EXISTS `post_responses` (
  `response_id` smallint(6) NOT NULL AUTO_INCREMENT,
  `post_id` smallint(6) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `response` text,
  `response_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`response_id`)

Right. Your problem is that your database is storing values in YYYY-mm-dd HH:MM:SS format, and your are comparing against the result of time() which is an integer.

Comparing apples and oranges doesn’t work.

Try date('Y-m-d H:i:s') instead of time()

@rpkamp. Thank you for the reply. I was very hopeful, but no change after adjusting that :frowning:

Curiouser and curiouser. I honestly don’t know what’s going on at this without testing myself, and I’m afraid I don’t have time for that the next few days.

Maybe someone else can give it a shot?

@rpkamp. Thank you anyway for your time and efforts. Very much appreciated

1 Like

Something like this…

if (isset($_GET['last_id'])) {
  $sql .= ' WHERE response_id > :last_id';
  $params['last_id'] = $_GET['last_id'];

… and in your JS you send the last response ID (or actually greatest, if ordered otherwise) in the query string. Alternatively you might store the last response ID in a server-side session variable.

1 Like

Don’t do that. Never solve with state that which can easily be resolved without state.


Good point. :-)

I just want to mention that polling is not the only way.
You could also set your PHP Server up to actively push new messages to the client. (E.g. Ratchet: http://socketo.me/)
Then you would save the overhead of actively asking for new messages.

However, as I see it, your problem is something else.

Please find out what you really get from your DB.
What is lastChecked?

Run the SQL Statement manually, if you verified that you get the correct data.
What do you get for SELECT * FROM post_responses WHERE response_date > 1528700000?
Try to work it out from there.
Hope that helps.

You can use Chrome DevTools to see what you are sending to the server and what you can get back. Make screenshots from the request and response data. Also: Make sure you actually get JSON, send JSON. etc.

1 Like

@MartinMuzatko. Thank you very much for the reply. For sure I’m goig to have a look at Ratchet: http://socketo.me. I think I found the problem with the polling. I am still testing, but if I know I will let you know.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.