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>
Note about PHP: it’s safer to use
<?php
and<?php echo
than<?
and<?=
.– brasofilo
Yes about php I know, but I wanted to know more about this ajax ai
– Lucas C.S
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/
– Marcelo Aymone
Luke, so I made only one Comment. A full explanation is published as Reply ;)
– brasofilo
I’ve read this post just wanted to get an analysis of that code of mine
– Lucas C.S
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.
– Marcelo Aymone
Got it Marty
– Lucas C.S
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.
– Lucas C.S