1
I am studying ajax, jquery and php. And in order to make a screen that loads automatically, for future chat. What I want to understand is the screen loading function.
I have index.php code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<?php
require "bd.php";
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
function autoRefresh_div()
{
$("#result").load("index.php").show();// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 4000);
</script>
</head>
<body>
<div id="result">
<?php
if($sql->rowCount() > 0){
foreach($sql->fetchAll() as $dados){
echo "mensagem: ".$dados['mensagem']."<br>";
}
}
?>
</div>
</body>
</html>
I have the code bd.php
<?php
$dsn = "mysql:dbname=realtime;host=localhost";
$dbname = "root";
$dbpass = "";
try{
$pdo = new PDO($dsn, $dbname, $dbpass);
}catch(PDOException $e){
echo "Erro: ".$e->getMessage();
}
$sql = "SELECT * FROM chat";
$sql = $pdo->query($sql);
?>
The problem that as time goes on, the screen hangs by the fact of sending several requests and this is making the server heavy and crashes the navigation screen. Is there anything I can improve the code to avoid this problem?
I advised you to use AJAX with json return which is good practice for applications of this type
– 13dev
could you give me an example, please
– Alan
I’ll give you an answer for a moment
– 13dev
Hello @Alan, in my reply I mentioned some topics that you should study to improve this process and also put the resolution of the most serious problem - which is causing this Overload on your server.
– Godfrey the King
Okay, I’ll study the concepts you gave me better. I’m studying more functions so I can use my logic for other things. Thank you very much!
– Alan
Websocket
... The problem is that vc will consume network resource by making several requests to the bank using the browser. I believe the best output is to usewebsocket
. If no one can answer, I’ll try...– ShutUpMagda
@Shutupmagda could create an answer showing how to do with websocket because no one showed anything yet with websocket, I think it would be interesting.
– user83428
@Viniciusputtimorais this answer is canonical... It has to work her right. It takes... That’s why I said that if no one tries to answer in a simple way, I’ll try to answer later ;)
– ShutUpMagda