TheQuestionerMan TheQuestionerMan - 4 months ago 21
jQuery Question

Combining Google Graph to PHP and AJAX

I want to build a dynamic graph that receives the data via the Yahoo finance and updated every few seconds automatically via PHP&AJAX integration to JS graph.

Can someone please tell me what the problem is here? How do I fix my code?

The main idea of the automatic graph is to get updates from the Yahoo Finance DATA API with PHP.

The full function:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Price'],

<?php
if(isset($_GET['fetchOnly'])){
$from = 'eur';
$to = 'usd';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {

while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['time'] = date("Y-m-d H:i:s");
}
fclose($handle);

}

echo "['";
echo $response['time'];
echo "', ";
echo $response['rate'];
echo "],";
}
?>

]);

var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};

var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

chart.draw(data, options);
}
</script>
</head>
<body>


<script>
// run the function, it will re-run itself
fetchRate();

function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("curve_chart")
div.innerHTML = div.innerHTML + ''+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + 'Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,10000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}
</script>


<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>

Answer

This:

<?php
    if(isset($_GET['fetchOnly'])){
    $from   = 'eur';
    $to     = 'usd';
    $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; 
    $response = array();
    $handle = fopen($url, 'r'); 
    if ($handle) { 

        while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE) 
        { 
            $response['time'] = date("Y-m-d H:i:s");
            $response['rate'] = $data[1]; 

        }
        fclose($handle);

    } 
     echo json_encode(array_values($response));
exit();
        } 
?>    
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
    var data;
    var chart;
    var options;
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        data = new google.visualization.DataTable();
        data.addColumn('date', 'Year');
data.addColumn('number', 'Price');

        options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' }
        };

        chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>


<script>
// run the function, it will re-run itself
fetchRate();

function fetchRate() {
    // create the new AJAX Object
    xmlhttp = new XMLHttpRequest();
    // this handles the request
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
            // if the request came back successfully
            if(xmlhttp.status == 200){
                // write the response to a div
                var got= JSON.parse(xmlhttp.responseText);
                got[0] = new Date(got[0]);
                got[1] = parseFloat(got[1]);
                data.addRow(got);


        chart.draw(data, options);
            }else{
            // if the request had an error
                div.innerHTML = div.innerHTML + 'Error fetching rates error code : '+xmlhttp.status;
            }
            // rerun this function to fetch updates
            setTimeout(fetchRate,10000);
        }
    };
    // open the AJAX Object
    xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
    // send the AJAX request
    xmlhttp.send();
}
</script>


    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>