Analysis on AJAX code

Asked

Viewed 470 times

1

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

pagina.html => page that occurs the automatic update

<!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 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>
  • 2

    Note about PHP: it’s safer to use <?php and <?php echo than <? and <?=.

  • 2

    Yes about php I know, but I wanted to know more about this ajax ai

  • What happens if there are more than five messages after the break? In case, you are using Ajax Polling, long Polling does not close the connection is waiting for the server to respond, not needing to reopen it every time interval, generating an excess of unnecessary requests. I recommend taking a look at this link http://imasters.com.br/artigo/23436/javascript/veja-como-o-long-polling-pode-helpr-a-development-real-time applications/

  • Luke, so I made only one Comment. A full explanation is published as Reply ;)

  • 1

    I’ve read this post just wanted to get an analysis of that code of mine

  • I also commented on your code. It generates unnecessary requests, processing consumption, bandwidth, unnecessary, if used in an app with many accesses, will have a poor performance. Working works, but not in the best way.

  • 1

    Got it Marty

  • 1

    brasofilo my doubt is that even the Mantlo is speaking the cons of the code and if there is something unnecessary in the code too.

Show 3 more comments

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:

  1. I write the message and send to you that was the kitchen and can not answer;
  2. Every 5 seconds the script makes a request to the server to see if you answered my message;
  3. You spent about 10 minutes in the kitchen, so that’s 12 requests per minute, that is, the script made 120 requests to the server without any need.
  4. You answered but wrote about 3 message in the interval of 5 seconds (quick right)
  5. Suddenly I get 3 message at once...

Now look at the problems:

  1. 120 requests were made and consumed server resources without any need because there was no response from you.
  2. Messages were pending because I only get one update every 5 seconds.
  3. Multiple connections at the same time making the same request will overload the server and may even "crash" it due to lack of memory to process all requests.

Long Polling would be different, in practice it would be like this:

  1. I write the message and send to you that was the kitchen and can not answer;
  2. The call is open waiting for a reply from you and no further requests until the answer arrives;
  3. You took about 10 minutes in the kitchen, but as there are only requisitions if there is an answer, only 1 requisition occurred.
  4. You answered but wrote about 3 message in the interval of 5 seconds (quick right)
  5. I get a reply at a time, because when you pressed to send the first message, there was a change on the server and the link that was pending returned a reply, closed the connection and then re-established the cycle.

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.

  • Perfect explanation.

  • 1

    Very good his explanation, I knew that this system in ajax was a thing of 7 even kkk head, but I just solved the problem with my long Lling here on the forum, I open!

  • @Lucasc. S is not a bug of 7 heads, just confuse it a little with ajax. But if it is to make a real time application, I suggest changing this part from php to nodejs, is more suitable.

2

The system is cool, Lucas. But to become long Polling, you need to add "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 to this type of Polling. But I find it much better than requesting it every 3 seconds, as is common in many chats around.

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

  • 1

    I understood even more about long Lling with his explanation =D

  • @Lucasc. S I used a lot, especially in queued systems such as notifications and chat. In chat, for example, the response time is practically real-time

Browser other questions tagged

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