Ajax Locking Page Exchange (Longpolling)

Asked

Viewed 504 times

5

I am trying to complete a connection using Long Polling, where the browser sends a request to the server and awaits a response. To avoid this door being open endlessly, I created a routine so that every 10 seconds the server sends an empty answer to the browser, stating that there was nothing so far.

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

My problem is that when the user clicks on some link on the page, the browser waits for the answer of the call to be able to update, that is, it can take up to 10 seconds. This makes it look like the tool is slow.

Does anyone have any idea how to fix this?

exemplo do longpolling funcionando o que acontece quando clico em um link

Follow 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;
    }
}

Follow the PHP function responsible for staying open waiting for some changes 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++;
    }
}
  • 2

    Is it possible to show partial information? or all the necessary information comes only once? I imagine you have one .png or .gif or message that something is happening on background. If not, it is important for the user to know that the page is handling the request.

  • 1

    You can show us your ajax call?

  • 1

    When vc opened the connection with the server using xmlhttp.open, vc uses Async TRUE or FALSE?

  • You could use Signalr with ASP.Net

  • I added the code used to facilitate. Thanks for all your help so far.

1 answer

1

Without looking at the way you’re sending it, we’re a little in the dark, but you can use Jquery’s $.ajax method by setting the async as TRUE or FALSE depending on need, TRUE = asynchronous and FALSE = NON-SYNCHRON.

I would do something like this:

I haven’t run tests on 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
    });
}
  • Thanks for the reply, I will post my code, but I do not use Jquery.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.