1

I want to ask a question in php. I want to make a plan and changing values over it. I put a image and I put some datas over it. I want to refresh auto this values.

<div class="container">
  <img src="ahol.PNG" alt="Norway" style="width:100%;">
  <div class="data1">$data1 kWh </div>
 <div class="data2">$data2 kWh </div>
   <div class="data3">$data3 kWh </div>
 <div class="data4">$data4 kWh </div>
</div>

This is my getting data php code in same file;

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM makinebilgi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {    
        $data1 =$row["data1"];
        $data2= $row["data2"];
        $data3= $row["data3"];
        $data4= $row["data4"];
    }
} else {
    echo "0 results";
}
$conn->close();

This page I want to use energy system watch. I am adding energy values to database every second. I want to autorefresh only datas not page.

10
  • 4
    You have to use ajax for it. Commented Dec 26, 2017 at 10:40
  • check this link regarding how to use ajax w3schools.com/php/php_ajax_php.asp Commented Dec 26, 2017 at 10:41
  • @AhsanAli do you have any example like it? Commented Dec 26, 2017 at 10:47
  • @kranthi I look it. Its not refreshing auto and its refreshing only one div id ?And Do I do for every data multiple or single? Is a query for every data ? Commented Dec 26, 2017 at 10:50
  • where is the data coming from originally? Commented Dec 26, 2017 at 10:53

2 Answers 2

7

You can achieve this using ajax.

Make data.php file and put your backend code:

<?php

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM makinebilgi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $data1 =$row["data1"];
        $data2= $row["data2"];
        $data3= $row["data3"];
        $data4= $row["data4"];
        echo "<img src='ahol.PNG' alt='Norway' style='width:100%;'>";
        echo "<div class='data1'>" . $data1  . "</div>";
        echo "<div class='data2'>" . $data2  . "</div>";
        echo "<div class='data3'>" . $data3  . "</div>";
        echo "<div class='data4'>" . $data4  . "</div>";
    }
} else {
    echo "0 results";
}
$conn->close();


?>

Update client side:

   <div class="container" id="output"></div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Make ajax call from client side:

<script>
    $(document).ready(function(){
        function getData(){
            $.ajax({
                type: 'POST',
                url: 'data.php',
                success: function(data){
                    $('#output').html(data);
                }
            });
        }
        getData();
        setInterval(function () {
            getData(); 
        }, 1000);  // it will refresh your data every 1 sec

    });
</script>
Sign up to request clarification or add additional context in comments.

Comments

4

When you need to continually fetch data from the database without reloading the page there are several options available - ajax, websockets and Server Sent Events probably being the most commonly used.

As the database is being updated by your c# app you do not need the full bi-directional capabilities offered by websockets nor does the querying of the database require parameters to be constantly sent so of these possible options my favourite would be SSE simply because it is so easy to setup and doesn't require constant ping-pong traffic ( request/response )

A very simple Server Sent Events script to query the database every n seconds and send the recordset as a payload to the javascript client.

<?php

    /* sse.php */

    set_time_limit( 0 );
    ini_set('auto_detect_line_endings', 1);
    ini_set('max_execution_time', '0');
    ob_end_clean();

    /*-------------------------------------------------------------------------*/
    $refresh=!empty( $_GET['refresh'] ) ? intval( $_GET['refresh'] ) : 1;
    $evtname=!empty( $_GET['evtname'] ) ? $_GET['evtname'] : 'sse';
    /*-------------------------------------------------------------------------*/


    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $db  = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    /* get last record ~ assumed `id` column being auto-increment */
    $sql='select * from `makinebilgi` order by `id` desc limit 1;';


    function sse( $evtname='sse', $data=null, $retry=1000 ){
        if( !is_null( $data ) ){
            echo "event:".$evtname."\r\n";
            echo "retry:".$retry."\r\n";
            echo "data:" . json_encode( $data, JSON_FORCE_OBJECT | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS );
            echo "\r\n\r\n";
        }
    }

    header('Content-Type: text/event-stream'); 
    header('Cache-Control: no-cache');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Expose-Headers: X-Events');


    while( true ){
        if( connection_status() != CONNECTION_NORMAL or connection_aborted() ) break;

        $payload=array();
        $result = $db->query( $sql );
        while( $rs=$result->fetch_object() ){
            $payload[]=$rs;
        }


        /* send the payload */
        call_user_func( 'sse', $evtname, $payload );


        /* -- Send output -- */
        if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @flush();


        /* wait for defined period before repeating loop */
        sleep( $refresh );

    } //end infinite loop


    if( @ob_get_level() > 0 ) {
        for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @ob_end_clean();
    }
?>

The client side code that uses some simple javascript to invoke the Server Sent Events script

<?php

?>
<!doctype html>
<html>
    <head>
        <title>sse display of data from c# app to db</title>
        <script>
            (function(){
                var options={capture:false,once:false,passive:false};

                document.addEventListener('DOMContentLoaded',function(event){

                    var url='/path/to/sse.php?refresh=1&evtname=sse';

                    var d1=document.getElementById('d1');
                    var d2=document.getElementById('d2');
                    var d3=document.getElementById('d3');
                    var d4=document.getElementById('d4');

                    if ( !!window.EventSource ) {

                        var evtSource = new EventSource( url );
                        evtSource.addEventListener( 'sse',function(e){
                            var json=JSON.parse( e.data );
                            var keys=Object.keys( json );
                            var obj=json[ keys[0] ];

                            console.info( json,keys );

                            d1.innerHTML=obj.data1;
                            d2.innerHTML=obj.data2;
                            d3.innerHTML=obj.data3;
                            d4.innerHTML=obj.data4;

                        },options );
                    }
                },options );
            })();
        </script>
    </head>
    <body>
        <div class='container'>
            <img src='ahol.PNG' alt='Norway' style='width:100%;'>
            <div id='d1' class='data1'></div>
            <div id='d2' class='data2'></div>
            <div id='d3' class='data3'></div>
            <div id='d4' class='data4'></div>
        </div>
    </body>
</html>

None of the above is tested but should be ok - though given the state of my hangover one never knows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.