0

I'm trying to develop a div that is automatically updated with your own content as it will be to show a real ping a website on canvas.
I have the following script:

<script> 
var auto_refresh = setInterval(
function()
{
$('#divcanvas').fadeOut('slow').load('teste.php #divcanvas').fadeIn("slow");
}, 1000);
</script>

In my markup have:

<div style="width:30%">
    <div id="divcanvas">
        <canvas id="canvas" height="450" width="600"></canvas>
    </div>
</div>

And in test.php have:

<?php 
include_once "ping/pingdomain.php";
require_once "ping/config.php";
$ms = pingDomain('www.adhenrique.com.br');
$hora = date("H:i:s", time());
mysql_query("insert into ping (resposta, horario) values ('$ms', '$hora')");
$sql = mysql_query("SELECT * FROM PING order by id DESC LIMIT 0,15");
?>
<head>
<title>Documento sem título</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="includes/js/chart.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    </head>
    <body>
    <canvas id="canvas" height="450" width="600"></canvas>
<?php
$pingreposta = array();
$pinghorario = array();
while($valor = mysql_fetch_assoc($sql))
{
    extract($valor);
    $pinghorario[] = $valor['horario'];
    $pingreposta[] = $valor['resposta'];
}
?>
    <script>
        var lineChartData = {
            labels :<?php echo '[' .'"'. implode('","', $pinghorario) .'"'. ']'; ?>
            ,
            datasets : [
                {
                    label: "My First dataset",
                    fillColor : "rgba(220,220,220,0.2)",
                    strokeColor : "rgba(220,220,220,1)",
                    pointColor : "rgba(220,220,220,1)",
                    pointStrokeColor : "#fff",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(220,220,220,1)",
                    data : <?php echo '[' . implode(',', $pingreposta) . ']'; ?>

                }
            ]

        }

    window.onload = function(){
        var ctx = document.getElementById("canvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            responsive: true
        });
    }


    </script>

    </body>
</html>

But when i open the index.php, it does not show the canvas. But if i open the test.php data it shows. That is, the code of canvas is correct.
Where is my mistake?

AD Henrique
  • 186
  • 2
  • 13

2 Answers2

1

At this line, you did a typo:

$('#divcanvas').fadeOut('slow').load('teste.php #divcanvas').fadeIn("slow");

teste.php should be test.php I guess.

Amar Syla
  • 3,523
  • 3
  • 29
  • 69
0

When you call load('teste.php #divcanvas') in that way you're requesting only #divcanvas from teste.php (which not exists) according to jQuery.load()

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

I would prefer this kind of approach using ajax

main.html

<!doctype html>
<body>
<head>
<title>Documento sem título</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="jquery.js"></script>
<script src="chart.js"></script>
</head>
<script>
$(document).ready(function(){
    $('#divcanvas').fadeOut('slow');

    // Set "active" to true to animate addData()
    var chartAnimation = {"active":false,"time":250,"currentTime":0,"currentIndex":0};
    var data = new Array();
    var label = new Array();

    var lineChartData = {
        labels: [],
        datasets : [{
            label: "My First dataset",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data: []
        }]
    };

    var canvas = document.getElementById("canvas");
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {
        responsive: true
    });

    $.get("test.php", function(res) {
        res = jQuery.parseJSON(res);
        $('#divcanvas').fadeIn("slow")
        for (var key in res) {
            var arr = new Array(res[key])
            data.push(arr);
            label.push(key);
            if (chartAnimation.active) {
                chartAnimation.currentTime += chartAnimation.time;
                setTimeout(function(){myLine.addData(data[chartAnimation.currentIndex],label[chartAnimation.currentIndex]); chartAnimation.currentIndex++;},chartAnimation.currentTime);
            } else {
                myLine.addData(arr,key);
            }
        }
    });

});
</script>
<div style="width:30%">
    <div id="divcanvas">
        <canvas id="canvas" height="450" width="600"></canvas>
    </div>
</div>
</body>

test.php

<?php 
include_once "ping/pingdomain.php";
require_once "ping/config.php";
$ms = pingDomain('www.adhenrique.com.br');
$hora = date("H:i:s", time());
mysql_query("INSERT INTO ping (resposta, horario) VALUES (".$ms.", ".$hora.")");
$sql = mysql_query("SELECT * FROM PING order by id DESC LIMIT 0,15");
$resp = array();
while ($valor = mysql_fetch_assoc($sql)) {
    $resp[$valor['horario']] = $valor['resposta'];
}
echo json_encode($resp);
?>

Chart animation added just for fun :)

DrKey
  • 3,365
  • 2
  • 29
  • 46