AJAX code analysis

1

I found this code, which is like a Long Polling , and wanted to know if I might have problems using it. And I also wanted to know the cons of this code if I use it.

pagina.html = > page that the automatic update occurs

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="iso-8859-1">
    <title>Untitled Document</title>
    <script src="ajax.js" language="JavaScript" type="text/javascript"></script>
    <script type="text/javascript">
    obj_online = new montaXMLHTTP();
    function Online(){      
        obj_online.open("GET","ultimasmensagens.php",true); // Na pagina ultimassenhas esta a programação que lista as informações do BD
        obj_online.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        obj_online.onreadystatechange = function(){
            if(obj_online.readyState == 4){
                document.getElementById("online").innerHTML = obj_online.responseText;
                clearTimeout(re);
                setTimeout("Online()",5000);
            }
        }
        obj_online.send(null);
        var re = setTimeout("reenvia()",10000);
    }
    </script>
</head>
<body onLoad="setTimeout('Online()',2000);">
    <div id="online">
    </div>
</body>
</html>

ajax.js

function montaXMLHTTP(){
    try{
        myObj = new XMLHttpRequest()
    }catch(e){
        myObj = new ActiveXObject("Microsoft.XMLHTTP"); 
    }
    return myObj;
}

ultimasmensagens.php = > page that lists the messages

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="iso-8859-1">
    <title>Untitled Document</title>
</head>
<body>
<? 
include 'config.php'; // conexao com o bd
$mensagens = mysql_query("SELECT * FROM mensagens order by idmensagem DESC limit 5") 
    or die (mysql_error());
while($minhalista = mysql_fetch_array($mensagens)){ ?>
    <?=$minhalista['titulo']?><br />
<? } ?>
</body>
</html>
    
asked by anonymous 25.03.2014 / 17:57

2 answers

6

This is not Long Polling and I do not recommend using the script by the following:

  • A connection to the server is established every 5 seconds, even without any changes to the server.

If this were a chat, in practice it would work like this:

  • I write the message and send it to you that went to the kitchen and can not respond;
  • Every 5 seconds the script makes a request to the server to see if you have answered my message;
  • You took in the kitchen about 10 minutes, so there are 12 requests per minute, that is, the script made 120 requests to the server without any need.
  • You replied but wrote about 3 messages within 5 seconds (fast right)
  • Suddenly I get 3 messages at once ...
  • Now look at the problems:

  • 120 requests were made and consumed server resources without any need because there was no response from you.
  • Messages were pending because I only get one update every 5 seconds.
  • Multiple connections at the same time making the same request will overwhelm the server, and may even "knock" it out of memory to process all requests.
  • Long polling would be different, in practice it would look like this:

  • I write the message and send it to you that went to the kitchen and can not respond;
  • The link is open waiting for a response from you and there are no more requests until the response arrives;
  • You took in the kitchen for about 10 minutes, but since there are only requests if there is an answer, only 1 request occurred.
  • You replied but wrote about 3 messages within 5 seconds (fast right)
  • I get one response at a time, because when you pressed to send the first message, there was a change on the server and the connection that was pending returned a response, closed the connection, and then reset it again.
  • See, only 1 request was made to the server, which consumed much less resources.

    This is a practical explanation, search for PHP + LONG POLLING, there are many examples.

        
    25.03.2014 / 18:45
    2

    The system is legal, Lucas. But to become long polling, you need to add the "long". Something like this:

    include 'config.php'; // conexao com o bd
    $count = 0;
    // 30 tentativas ou 30 segundos até encontrar a primeira atualização.
    while ($count < 30) {
        // Adicione um campo em WHERE para saber se a mensagem é nova. O ideal é uma data
        $mensagens = mysql_query("SELECT * FROM mensagens WHERE creation > '$ultimaAtualizacao' order by idmensagem DESC limit 5")  or die (mysql_error());
        while($minhalista = mysql_fetch_array($mensagens)){
            echo $minhalista['titulo'];
            break;
        }
    
        // Não sobrecarregue seu banco. Espere 1 segundo antes de uma nova tentativa.
        sleep(1);
        $count++;
    }
    

    There are many pros and cons in this type of polling. But I find it far better than requesting every 3 seconds, as is common in many chats out there.

    The use of the websocket for is still unstable and does not work in all browsers. I still prefer the long polling along with nodejs

        
    25.03.2014 / 19:22