Function has real-time screen, lock the screen with time!

1

I'm studying ajax, jquery and php. And with the goal of making a screen that loads automatically, for future chatting. What I want to understand is the screen loading function.

I have the 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 bd.php code

<?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 according to time, the screen hangs because it sends several requests and this is leaving the server heavy and locks the navigation screen. Is there anything I can improve on the code to avoid this problem?

    
asked by anonymous 24.08.2017 / 20:03

4 answers

2

The problem is that you make a connection and at small intervals and leave it open.

Correct in this situation would be to use ajax with return from json which consumes less of the server So I'll give you a small example:

On the server side (PHP)

Create a separate file as connection.php with the DB connection:

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

then in the index.php file include the connection.php file in it, like this:

<?php

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

Do not forget to close the connection, for example:

$pdo = null;

At the end of all things, it returns all the data in json using the function json_encode()

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

In 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 setTimeout will do the ajax request to index.php with a 4-second interval and will receive json formatted data where you can start building the html with it!

    
24.08.2017 / 20:53
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 it over time gets overwhelmed.

Do the following, 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);

Attention !!!

There are lots of problems with your code, from critics to non-critics. Which I approached, is what will greatly reduce the overload of your server. However, for teaching purposes (since you are studying), I will give you all the problems and it would be nice to study them:

  • You are using PHP code in HTML (this is not a good practice)
  • Instead of using this PHP code in HTML ( $sql->rowCount(), etc ), in the index.php file itself make the select result flip JSON using the json_encode() PHP function.
  • Instead of using the jQuery function load() , use $.ajax, $.get, $.getJSON ... To study more about this third item, access this link
  • 24.08.2017 / 20:40
    2

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

    The setInterval , in your case, will run the function after 4 seconds regardless whether Ajax has been processed or not. This is very bad because if the Ajax return takes longer than the set time, it will send another request, and another and another and another ... causing chaos in both the server and the browser.

    The correct thing is you do a setTimeout("autoRefresh_div()",4000); after Ajax return.

    Basic difference between setInterval and setTimeout :

    • SetInterval : runs uninterrupted the function after the set time.
    • SetTimeout : executes only once the function after the set time.
    24.08.2017 / 20:56
    1

    If you are using ajax, then you should have a callback function, try instead to use setInterval to make a new request in the request callback function:

    // 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 do not know the syntax of jquery.

        
    24.08.2017 / 20:15