Function has screen in real time, hangs the screen with time!

Asked

Viewed 559 times

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

  • could you give me an example, please

  • I’ll give you an answer for a moment

  • 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.

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

  • 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 use websocket. If no one can answer, I’ll try...

  • 1

    @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.

  • @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 ;)

Show 3 more comments

4 answers

3

One of the most serious problems that is causing the crash, is that you, every 4000 milliseconds (4 seconds) are opening a new connection to the database! That’s why he gets overwhelmed with time.

Do this in a separate db.php file

<?php
$dsn = "mysql:dbname=realtime;host=localhost";
$dbname = "root";
$dbpass = "";
try{
    $pdo = new PDO($dsn, $dbname, $dbpass);
}catch(PDOException $e){
    echo "Erro: ".$e->getMessage();
}

Call this file only once, to connect it to the database, and keep your index.php (the file that will be used in your Ajax request):

<?php
$sql = "SELECT * FROM chat";
$sql = $pdo->query($sql);

Heed!!!

There are numerous problems with your code, from critical to non-critical. Which I addressed, is what will greatly decrease the overhead of your server. However, for educational purposes (since you are studying), I will give you all the problems and with that it would be nice to study them:

  1. You are using PHP code in HTML (this is not good practice)
  2. Instead of using this PHP code in HTML ($sql->rowCount(), etc), in the index.php file itself make the result of select turn JSON using the function json_encode() of PHP.
  3. Instead of using the jQuery function load(), use the $.ajax, $.get, $.getJSON ... To learn more about this third item, visit this link

2


The problem is you make a connection and at short intervals and leave the same open .

The most correct thing in this situation would be to use ajax with return of json what consumes less of the server So let me give you a little example:

On the server part (PHP)

Create a part file as connection.php with the connection to DB:

<?php
$dsn = "mysql:dbname=realtime;host=localhost";
$dbname = "root";
$dbpass = "";
try{
    $pdo = new PDO($dsn, $dbname, $dbpass);
}catch(PDOException $e){
    echo "Erro: ".$e->getMessage();
}

later in the index.php file includes the Connection.php file in the same, so:

<?php

include('connection.php');
$sql = "SELECT * FROM chat";
$sql = $pdo->query($sql);

Don’t forget to close the connection, example:

$pdo = null;

At the end of having everything ready returns all data in json using the function json_encode()

return json_encode(['dado1' => 'valor1', 'dado2' => 'valor2']);

On the client side (javascript/jquery)

 $(document).ready(function(){
    setTimeout(function(){
     $.ajax({url: "index.php", success: function(data){
                    // receber o json
                    var data = JSON.parse(data);
                    // daqui podes usar o json assim
                    $("#dado1").append(data.dado1);
            }});
     }, 4000);
});

Then the setTimeout will make the ajax request to index php. with 4 seconds interval and will receive data formatted in json where you can start building html with the same!

  • setInterval will overload... reference

  • @Shutupmagda Edited, thanks for the warning!

2

Of course it will. The setInterval is not appropriate for this.

The setInterval, in your case, will perform the function after 4 seconds regardless whether Ajax was sued or not. This is bad because, in case the return of Ajax takes longer than the time set, it will send another request, and other and other and other... causing chaos both on the server and in the browser.

What’s right is you make one setTimeout("autoRefresh_div()",4000); after the return of Ajax.

Basic difference between setInterval and setTimeout:

  • SetInterval: executes uninterruptedly function after set time.
  • SetTimeout: executes only once function after set time.
  • I thought about it when I mentioned the question there. But I still believe that the way out for him is websocket.

  • @Shutupmagda Tb think. I have no knowledge of the websocket, but I read something about it and it seems to be much better for the purpose.

1

If Voce is using ajax, then Voce must have a callback function, try instead of using setInterval to make a new request in the callback function of the requirements:

// Nao sei como faz ajax no jquery mas deve ser mais ou menos assim
ajax(url, function () {
    //essa funcao vai executar quando terminar essa requisicao ajax
    nova_requisicao();
}, data);

It’s just an example because I don’t know the jquery syntax.

Browser other questions tagged

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