Viewed   267 times

First things first, I am trying to parse the data from a data.php file that uses json encode to echo a datapoint. The datapoint is updated every time the data.php file is requested, but not in a series of datapoints. Instead it just changes the time value and refreshes its y content. I haven't found a working way to actually make the php file echo series of datapoints and not update a single one.

Next up, the chart parses the data.php file and it indeed shows the datapoint. BUT I want to make this chart update every second and add new datapoints on every update so that I have a working bandwidth graph.

Here is my code:

index.php:

<!DOCTYPE HTML>
<html>
<head>  
<script type="text/javascript" src="canvasjs.min.js"></script>
  <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
    <script>
$(document).ready(function () {
$.getJSON("data.php", function (data_points) {
    var dps = data_points
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
panEnabled: true,
animateEnabled: true,
data: [ {
type: "splineArea",
xValueType: "label",
y: "y",
dataPoints: dps } ]
});
chart.render();
});
});
</script>
</head>
<body>
    <div id="chartContainer" style="height: 300px; width: 100%;">
    </div>
</body>
</html>

data.php:

<?

session_start();
session_destroy();
session_start();

$rx[] = @file_get_contents("/sys/class/net/wlan0/statistics/rx_bytes");
sleep(1);
$rx[] = @file_get_contents("/sys/class/net/wlan0/statistics/rx_bytes");

$rbps = $rx[1] - $rx[0];

$round_rx=round($rbps/1, 2);

$time=date("Y-m-d H:i:s");
$_SESSION['rx'] = $round_rx;
$data_points['label'] = $time;
$data_points['y'] = $_SESSION['rx'];

echo json_encode([$data_points]);

?>

If anyone know on how to make this map dynamic then please provide me some help. An example output of the data.php file (what it echoes) is the following:

[{"label":"2015-09-12 21:34:12","y":1500}]

Thank you in advance for any help provided.

 Answers

5

In order to update charts that way, you need to create chart only once (outside the ajax request) and keep adding new dataPoints via ajax request each second as shown below.

<!DOCTYPE HTML>
<html>
    <head>  
        <script type="text/javascript" src="canvasjs.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                var chart = new CanvasJS.Chart("chartContainer", {

                    zoomEnabled: true,
                    panEnabled: true,
                    animateEnabled: true,
                    data: [ {
                        type: "splineArea",
                        xValueType: "label",
                        y: "y",
                        dataPoints: [] 
                    } ] 

                });

                function updateChart(){
                    $.getJSON("data.php", function (data_points) {
                        for(var i = 0; i < data_points.length; i++){
                            chart.options.data[0].dataPoints.push(data_points[i]);
                        }

                        chart.render();
                    });
                }               

                var updateInterval = 1000;

                setInterval(function(){
                        updateChart()
                }, updateInterval);

            });

        </script>
    </head>
    <body>
        <div id="chartContainer" style="height: 300px; width: 500px;"></div>
    </body>
</html>
Friday, December 2, 2022
 
1

When dealing with jQuery AJAX using a data type of JSON, any notice, warning or error produced by the server side script will cause issues. The reason being is the outputted PHP errors break the JSON encoding that jQuery is expecting.

I suspect the two environments are not identical, perhaps a different PHP version, missing PHP extension or different settings in the php.ini file.

The best thing to do is to use the provided jQuery AJAX error callback to console log any errors allowing you to essentially troubleshoot any issues being thrown by the server side script.

!!! EDIT 3 !!!

Client Code

$.ajax({
    type: "POST",
    dataType: "json",
    url: "http://myurl.com/jsonpost.php", 
    data: data,
    success: function(response) {
        console.log(response);
    },
    error: function(xhr, status, error) {
       console.log(xhr);
       console.log(status);
       console.log(error);
    }
});

Server Side Code

header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

echo json_encode(array('success' => 'yes'));

Using this bare bones version of your code I can successfully make a cross domain request and console log the response. If you implement this code and it still does not work there is something else at play at the server and/or network level.

Sunday, September 11, 2022
1

Try base64_encoding it like such:

$value = array(
    'utm_source' => 'website',
    'utm_medium' => 'fbshare',
    'utm_campaign' => 'camp1',
    'test_cat' => 'red',
    'test_sub' => 'Category',
    'test_ref' => 'rjdepe'
);
$value = base64_encode(json_encode($value));
setcookie("TestCookie", $value, time()+3600);

Other Page:

$cookie = $_COOKIE['TestCookie'];
$cookie = json_decode(base64_decode($cookie));
print_r($cookie);
Wednesday, August 10, 2022
 
mcls
 
4

Writing data back to PHP is not possible afaik because PHP is evaluated on serverside and the client just gets its resulting page. But here is a solution with JavaScript, which is only running on the client side:

As you should know your result looks something like this:

[
{
    "id": "bitcoin", 
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "17391.5", 
    "price_btc": "1.0", 
    "24h_volume_usd": "15047800000.0", 
    "market_cap_usd": "291076752838", 
    "available_supply": "16736725.0", 
    "total_supply": "16736725.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "-0.14", 
    "percent_change_24h": "3.75", 
    "percent_change_7d": "45.85", 
    "last_updated": "1513104255", 
    "price_eur": "14834.288623", 
    "24h_volume_eur": "12835201583.6", 
    "market_cap_eur": "248277409254"
}, 
....
]

It's an Array of objects where each object contains the following properties (id, name, symbol, ... , market_cap_eur).

To display all those you would need to loop through the array and create some kind of dispalytemplate for the objects.

Therefore you should replace the following line of code in the registered onreadystatechange-function:

document.getElementById("collect").innerHTML = obj;

with something like:

var objlength = obj.length;
var element = document.getElementById("collect");
element.innerHTML = "";
for ( var i = 0; i < objlength; i++){
    element.innerHTML += JSON.stringify(obj[i])+"<br />";
}

This would create a stringified result for each cryptocurrency in a new line. The result of it will still be unreadable and the code to setup the innerHTML is really dirty. To enhance atleast the display even more, you could do something like:

var objlength = obj.length;
var element = document.getElementById("collect");
element.innerHTML = "";
for ( var i = 0; i < objlength; i++){
    element.innerHTML += obj[i].name+" is "+ obj[i].price_eur +"<br />";
}

which should return the name of the curreny and the current EUR price per line. You can extend this by all desired properties.

But as mentioned it's quick and dirty and please don't judge me by this code.

Also you need to delete the + Math.Random() in you request. Here is a working live example: http://plnkr.co/edit/aHXFVAjH6qoKk2vmOf0u?p=preview

Thursday, September 8, 2022
 
pesla
 
3

I've not tried. But i guess it may work.

    JSONObject obj = new JSONObject(jsonString);
    String id = obj.getString("id");
    String error = obj.getString("error");
    JSONObject result = obj.getJSONObject("result");
    int nPeople = result.getInt("nPeople");
    JSONArray people = result.getJSONArray("people");
    for(int i = 0 ; i < people.length() ; i++){
        JSONObject p = (JSONObject)people.get(i);
        String namePeople = p.getString("namePeople");
        ...
    }
Saturday, October 15, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :