2

I'm trying to implement a long polling system on my intranetwork, most of the users use IE and some use mobile too, that's why I'm trying to do it with long polling and not with websockets.

I followed this video http://www.screenr.com/SNH and I edited some code to work with my database. (Firebird)

It all seems ok, but it just doesn't break the loop. Maybe it's a kid mistake but I cannot see it, that is why I need your help!

Here's the code:

jQuery + Ajax:

var timestamp = null;

function waitForMsg(){      
    $.ajax({
        type: "GET",
        url: "getData.php?timestamp=" + timestamp,
        async: true,
        cache: false,

        success: function(data){
            alert('It Works');
            var json = eval('(' + data + ')');
            timestamp = json['timestamp'];
            setTimeout('waitForMsg()',15000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            alert("A - " + XMLHttpRequest + " - error: " + textStatus + " (" + errorThrown + ")");
            setTimeout('waitForMsg()',15000);
        }
    });
}

$(document).ready(function(){
    waitForMsg();
});

</script>

getData.php ('DATAHORA' is timestamp field)

<?php
    set_time_limit(0);
    @ini_set("memory_limit",'64M');

    require_once('../classes/conexao.php');

    $banco = Conexao :: getConexao();
    $sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
    $res = $banco->execute($sql);
    $dados = $banco->fetch($res);
    if($dados)
        $currentmodif = $dados['DATAHORA']);
    else
        $currentmodif = 0;

    $lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;

    while( $currentmodif <= $lastmodif ){
        usleep(10000);
        $sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
        $res = $banco->execute($sql);
        $dados = $banco->fetch($res);
        if($dados)
            $currentmodif = $dados['DATAHORA']);
        else
            $currentmodif = 0;
    }

    $response = array();
    $response['timestamp'] = $currentmodif;
    echo json_encode($response);

?>

When I insert, update, or delete some data, the timestamp field are updated with the current timestamp. I can see that the page enters the loop, but I don't know why it never ends.

Am I doing something wrong?

Thank you

2
  • eval()? Why eval the json, when jquery already has perfectly good built-in JSON-handling? As well... why should the loop ever quit? In both your success and error code paths, you unconditionally reschedule the waitForMsg() on every iteration - there's no way for the loop to exit. If you want it to quit, you have to give it some way TO quit. Commented Sep 16, 2013 at 15:08
  • @MarcB I just followed the video tutorial, thats why the eval() and the rest. It works like a charm if i try the same code but using a file and filetime. In this code, if a new information is added in the database, it should exit the loop and pass the json value, and then return to the page with the loop. Commented Sep 16, 2013 at 15:15

6 Answers 6

2

I finaly found the solution.

And it was so simple. My code was not closing the connection with ibase_close

What i did was change it to close when finish the query process. Then inside the loop, i need to reconnect the server again.

OMG how could i forgot that.

Thanks everyone.

Sign up to request clarification or add additional context in comments.

Comments

1

Try replacing $currentmodif = $dados['DATAHORA']); with $currentmodif = $dados['HORA']); inside the while loop.

You're asking for an array key that doesn't exist, which will always be null, so your loop will run forever if $lastmodif is not null.

1 Comment

Sorry bro, but with your answer that I saw that I had mistyped the sql line, but thanks anyway
1

Change $currentmodif = $dados['DATAHORA']);, look:

<?php
set_time_limit(0);
@ini_set("memory_limit",'64M');

require_once('../classes/conexao.php');

$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
    $currentmodif = $dados['DATAHORA']);
else
    $currentmodif = 0;

$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;

while( $currentmodif <= $lastmodif ){
    usleep(10000);
    $sql = "SELECT FIRST 1 DATA, HORA FROM AGENDAMENTOSBBM ORDER BY DATA DESC,HORA DESC";
    $res = $banco->execute($sql);
    $dados = $banco->fetch($res);
    if($dados)
        $currentmodif = $dados['DATA'].$dados['HORA']; // Before : $dados['DATAHORA']);
    else
        $currentmodif = 0;
}

$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);

?>

I don't know how look of your database design so, i suggest to you to change by yourself Maybe your mistakes are on that lines. But i can't decide, because i have no time to fix it, i must do my project. If i'm wrong, I'm sorry. Good luck

1 Comment

Sorry bro, but with your answer that I saw that I had mistyped the sql line, but thanks anyway
1

After rewriting the code in MySQL and scratching my head over why it seemed to be working just fine, I found the problem:

You need to set your initial var timestamp to 0, not null. If you set it to null, jQuery will send it as the string "null" (?timestamp=null). In PHP, it will compare this string "null" to whatever number $currentmodif is, so in the end you will never get into your while loop.

6 Comments

I already tried that, and it's always the same. Infinity loop and nothing happens :(
Once it enters the loop, are you inserting a new row into the table with the higher timestamp than the previous one? Because it seems to work...
In another page, I insert data in the table with a higher timestamp or I update a row also with a higher timestamp. Check my others comments here, i already tried to do manualy and it not worked too.
So going by the other comments and this, you've changed timestamp to 0, you enter the loop, then manually insert a timestamp, confirm that you get the new timestamp $dados and $currentmodif is updated, and you're still stuck in the loop?
The query looks fine, but I'm not familiar with firebird. Like I said, it works fine with MySQL; maybe the result from the first query is being cached somewhere?
|
0

Try to eval your queries and see what they return, so you can validate the returned data and ensure the array $dados has the needed data and the keys to access any data of the array $dados.

1 Comment

If I use something like a var_dump($dados) i can see that it returns exactly what I need. And if i simulate passing manualy the data or use a flag to stop the` while, it works, but still not does any changes on $currentmodif` inside the loop
0
var longpollError = false;
function longPoll(){
    $.ajax({
        url: "socialPolling",
        type: 'GET',
        dataType: 'json',
        data: {param1: 'value1'},
        timeout: 30000 // timeout every 10 sec
      }).done(function(dataJson) {

        //Success code goes here

      })
      .fail(function(data) {
         longpollError = true; //mark this to true if there is an error

      }).always(function(data) {
        if(longpollError==false){ //if there is no error request it again
          setTimeout(function() {
            longPoll();
          }, 3000);

        }

      })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.