Ajax locking page exchange (LongPolling)

4

I am trying to complete a connection using Long Polling, where the browser sends a request to the server and is waiting for a response. To prevent this port from being infinitely open, I created a routine so that every 10 seconds the server sends an empty response to the browser, stating that nothing has been done yet.

Everything working perfectly, I had no problem related to that.

My problem is that when the user clicks on a link on the page, the browser waits for the call to be able to refresh, that is, it can take up to 10 sec. This makes it look like the tool is slow.

Does anyone have any idea how to solve this?

Here is the JavaScript function used to make the call:

function loadJSON() {

    if(libera) {

        var data_file = http + "bibliotecas/longpolling/notificacoes.php";

        var data = {};
            data.n = long_n;
            data.u = userchat;
            data.m = msgchat;
            data.c = chatUsuario;

        http_request.onreadystatechange  = function() {

            if(http_request.readyState == 4 && http_request.status == 200) {

                try {
                    var jsonObj = JSON.parse(http_request.responseText);
                    var qtd = jsonObj.funcao.length;
                    if(qtd > 0) {
                        var funcao = "";
                        for(var key in jsonObj.funcao) {
                            funcao = jsonObj.funcao[key];
                            MontarFuncao(eval(funcao),jsonObj.metodo[key]);
                        }
                    }
                }
                catch (e) {
                    //alert('Erro - '+ http_request.responseText);
                }

                loadJSON();
            }
        }

        var string = JSON.stringify(data);

        http_request.open("POST", data_file, true);
        http_request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        http_request.setRequestHeader("Content-length", string.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(string);  

        return;
    }
}

Here is the PHP function responsible for being left waiting for some change in the database:

ob_start();
$json = json_decode(file_get_contents('php://input'));

while($x < 5) {

    if(time() >= (15 + $_SERVER['REQUEST_TIME']) || connection_aborted()) {
        echo str_pad(NULL,1);
        die(json_encode(array()));
        flush();
        ob_flush();
        break;
    }

    //Funções de consulta ao BD (Se houver algo adiciona Array no variavel $retorno)

    if(count($retorno) > 0) {
        flush();
        ob_flush();
        echo json_encode($retorno);
        exit;           
    }
    else {
        flush();
        sleep(2);
        $x++;
    }
}
    
asked by anonymous 17.10.2014 / 16:03

1 answer

1

Without looking at the form you are sending, we are in the dark, but you can use the $ .ajax method of JQuery by setting async to TRUE or FALSE depending on need, TRUE = asynchronous, and FALSE = NOT asynchronous.

I would do something like this:

  

I did not test the code, but I think it should work ...

$(document).ready(function(){    
    setInterval(function(){rServer('',true)},10000);

    $('.link').click(function(){
        clearInterval(rServer);
        var notificacoes = {n:3, u:'alguma coisa'};
        rServer(vars,false);
        setInterval(function(){rServer('',true)},10000);
    });
});

function rServer(vars,asyncStatus){
    $.ajax({
        url: script.php, // url do seu script
        type: "POST",// método HTTP utilizado
        data: vars, // parâmetros que serão enviados, no seu exemplo {n:3,u=''}
        dataType: "Json", // forma de recebimento da resposta
        async: asyncStatus
    }).done(function(data) {
        // **data** devolve as repostas do servidor
        // ação depois da reposta do servidor
    });
}
    
20.10.2014 / 16:10