I'm having some problems with importing a csv in order to get the highstock graph.
I'm using the same code as the ohlc example (which works fine locally) but with another CSV which is created on my localhost by php.
PHP to get the CSV
<?PHP
// Declare the new variable as an array
$arrCSV = array();
// Open the CSV file
if (($handle = fopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=7&e=7&f=2012&g=d&a=8&b=7&c=1984&ignore=.csv", "r")) !==FALSE)
{
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//print $c . "<BR>"; // <------ 7 o numero de colunas
//Populate the array
If ($key != 0) {
$arrCSV[$key-1][0] = strtotime($data[0])*1000; //Time
$arrCSV[$key-1][1] = $data[1]; //Open
$arrCSV[$key-1][2] = $data[2]; //High
$arrCSV[$key-1][3] = $data[3]; //Low
$arrCSV[$key-1][4] = $data[6]; //Adj Close
$arrCSV[$key-1][5] = $data[5]; //Volume
}
$key++;
} // end while
$keymax = $key;
// Close the CSV file
fclose($handle);
} // end if
print "?(/* AAPL historical OHLC data from the Google Finance API */<BR>";
echo json_encode($arrCSV,JSON_NUMERIC_CHECK);
print ");";
?>
Code to import and create the graph:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('http://localhost/teste03.php', function(data) {
console.log("1");
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 2
},
title : {
text : 'AAPL Stock Price'
},
series : [{
type : 'ohlc',
name : 'AAPL Stock Price',
data : data,
dataGrouping : {
units : [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
In the end it just get me a blank page...
On the chrome console I'm not able to get the console log that is inside the getjson and it reports as if everything is ok:
[23:39:29.980] GET http://localhost/TraderMananger/Highstock/ohlc4.htm [HTTP/1.1 304 Not Modified 1ms]
[23:39:30.036] GET http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js [HTTP/1.1 304 Not Modified 87ms]
[23:39:30.055] GET http://localhost/TraderMananger/Highstock/js/highstock.js [HTTP/1.1 304 Not Modified 1ms]
[23:39:30.073] GET http://localhost/TraderMananger/Highstock/js/modules/exporting.js [HTTP/1.1 304 Not Modified 1ms]
[23:39:30.219] GET http://localhost/TraderMananger/Highstock/teste04.php [HTTP/1.1 200 OK 2056ms]
Help?
Thanks
It is solved now, the issue was in the chos added before and after the json_encode, there is no need to add them
print "?(/* AAPL historical OHLC data from the Google Finance API */<BR>";
echo json_encode($arrCSV,JSON_NUMERIC_CHECK);
print ");";
So, removing them it solved the issue.
Related
I want to insert data to get sales report from two table into google chart. I have tried join query in model page, but the result is No Data in pie chart div.
Data from table sales is like below
id | person_name | sales_id | status
1 Michael 2 1
2 Daniel 2 3
3 James 2 1
4 Ricky 1 2
5 Martin 1 3
The data from table status is like below
id | status | color
1 Meeting #f00630
2 Presentation #f2478f
3 Proposal Sent #170303
4 Invoice #7cb342
5 Lost #fe0725
I need to insert data status type, total status (in number), and color status into google pie chart based on sales id. I need to change data which I write manually like below
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
['Meeting', 2],
['Presentation', 0],
['Proposal Sent', 1],
['Invoice', 0],
['Lost', 0]
]);
var options = {
is3D: true,
colors: ['#f00630', '#f2478f', '#170303', '#7cb342', '#fe0725']
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Here is the script I have tried in model page
public function getAllStatus()
{
$this->db->select('status');
$this->db->from('sales');
$this->db->join('sales_status', 'sales_status.id = sales.status');
$this->db->where('sales_id', $id);
return $query = $this->db->get();
}
Here's script in controller page
$data['sales'] = $this->Sales_model->getAllStatus()->result();
And here's the script in view page
var data = google.visualization.arrayToDataTable([
['Type', 'Total'],
<?php
foreach ($sales as $sale){
echo "['".$sale->name."',".$sale->count."],";
}
?>
]);
<div id="chart_div" style="width: 100%; "></div>
Do you know where's I need to fix ?
Thank you
The chart expects JSON objects with the data. You can try to build JSON-like structures with loops like you did, but it's much simpler to just output the JSON objects.
In your view, before the call to the chart is made:
var first_data = <?php echo json_encode($your_first_var); ?>;
var second_data = <?php echo json_encode($your_second_var); ?>;
then, when you actually invoke the JS that will draw the chart:
function drawChart() {
var data = google.visualization.arrayToDataTable(first_data);
var options = {
is3D: true,
colors: second_data
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I'm trying to plot graph on real time data on my website according to there patient_id in select tag.
In phpmyadmin database i have four column (temp,rate,date,patient_id)
in followdata_temp i getting data of temp as per time.
in main page i'm gettin select option as well as graph below it but I'm not able to plot graph on it.
// followdata_temp.php (from where data is fetched)
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//query to get data from the table
session_start();
//$pid = $_POST['patient_id'];
//echo $pid;
$query = sprintf("SELECT time, temp FROM heart_reating where patient_id='$pid' ") or die(mysql_error()); //$pid is where patient_id is declared in page.
//execute query
$result = $mysqli->query($query);
my html page
<html>
<head>
<title>ChartJS - Line</title>
<meta charset="utf-8"/>
<link href="css/default.css" rel="stylesheet">
</head>
<body>
<div class="chart-container">
<canvas id="line-chartcanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js2/jquery.min.js">
</script>
<script type="text/javascript" src="js2/Chart.min.js">
</script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js">
</script>
<script>
$(document).ready(function() {
/**
* call the data.php file to fetch the result from db table.
*/
$.ajax({
url : "/followdata_temp.php",
type : "GET",
success : function(data){
console.log(data);
var time = [];
var temp = [];
var len = data.length;
for (var i = 0; i < len; i++) {
time.push("" + data[i].time);
temp.push(data[i].temp);
}
//get canvas
var ctx = $("#line-chartcanvas");
var chartdata = {
labels : time,
datasets : [
{
label : "Temperature",
data : temp,
backgroundColor : "blue",
borderColor : "lightblue",
fill : false,
lineTension : 0,
pointRadius : 5
}
]
};
var chart = new Chart( ctx, {
type : "line",
data : chartdata
});
},
error : function(data) {
console.log(data);
}
});
});
</script>
</body>
</html>
I wanted plot graph by selecting patient id from select that is in phpmyadmin plot graph of it as (temp, time)
I perform the php script to show random data. I use ajax get to get data from the php script and continue getting data from the php script every 1 seconds. I also perform removal of the last row if the count is more or eqaul to 4. HOwever, my output is backward. I want to append new data before old data.
php script
<?php
$countryarr = array("UNITED STATES", "INDIA", "SINGAPORE","MALAYSIA","COLOMBIA","THAILAND","ALGERIA","ENGLAND","CANADA","CHINA", "SAUDI ARABIA");
$length = sizeof($countryarr)-1;
$random = rand(0,$length);
$random1 = rand(0,$length);
$random_srccountry = $countryarr[$random];
$random_dstcountry = $countryarr[$random1];
echo "<div>[X] NEW ATTACK: FROM [".$random_srccountry."] TO [".$random_dstcountry."] </div>";
?>
html code
<html>
<head>
<title>Add new data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#result {
width: 500px;
height:500px;
border-style: solid;
border-color: black;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
var $auto_refresh = setInterval(function() {
var $count = $('#result div').length;
while ($count >= 4) {
$('result div:last-child').remove();
$count = $('#result div').length;
}
updateServer();
}, 1000);
//Remove last div if the count is more than 4
function updateServer() {
$.get({
url: 'randomData.php',
dataType: 'text',
success: randomdata
});
}
function randomdata(val) {
$('#result').append(val); //i want to insert before in other words new data appear at the top and old data remain down
}
</script>
</body>
</html>
I thought of using before or insertbefore to insert new data before the old data. I also used node to insert before.It does not work. Please help me. thank you..
You have to use prepend() from jquery :
function randomdata(val) {
$('#result').prepend(val);
}
EDIT
I noticed an other error : $('result div:last-child').remove(); should be $('#result div:last-child').remove();
That's probably why it don't change, when it's at 4 divs it doesn't delete and redo the count, so you get stuck inside the while ... The fix from below should solve the problem
I want to retrieve data from a database which is locally installed.
But the website is written and controlled with js, so I have to send an ajax request to a php-file, which then connects to the database, sends the query and later the result back to js.
I have a couple of files, because i followed this tutorial from 2012: https://www.youtube.com/watch?v=Yb3c-HljFro
The structure:
|-ajax (Folder)
| |-pkmn.php
|-db (Folder)
| |-connect.php
|-js (Folder)
| |-global.js
|-index.php
The files:
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meta>
</head>
<body>
Type: <input type="text" id="type"></input>
Tier: <input type="text" id="tier"></input>
<input type="submit" id="submit" value="Suchen"></input>
<div id="pkmn-data"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
global.js:
$("#submit").click(function () {
var type = $("type").val();
$.ajax("ajax/pkmn.php", {type: type}, function(data) {
alert(data);
});
});
connect.php
<?php
mysql_connect('localhost','root', '123456');
mysql_select_db('database');
pkmn.php:
<?php
echo 'Hello';
The user should enter something into the text-inputs, then click submit and the global.js-file sends that text to the file pkmn.php via an ajax request.
But when I click the submit-button, I receive an error:
XML-Verarbeitungsfehler: Ungeschlossenes Token
Adresse: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/pkmn.php
Zeile Nr. 1, Spalte 1: pkmn.php:1:1
XML-Verarbeitungsfehler: Ungeschlossenes Token
Adresse: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/index.php
Zeile Nr. 1, Spalte 1: index.php:1:1
Which says something like:
XML-Parseerror: unclosed token
at: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/pkmn.php
Row 1, Column 1: pkmn.php
XML-Parseerror: unclosed token
at: file:///C:/Users/Jonathan%20Frakes/Documents/testDB/ajax/index.php
Row 1, Column 1: index.php
I have absolutely no idea, what could cause this error.
Furthermore: When I close the php-tag in pkmn.php the console says BOTH errors moved to Row 3 Column 3 and when I close the php-tag one line later (by adding another newline) the error again moves in both files one down. I can also add spaces in front of the closing tag, moving the errors horizontally.
I have never seen something like this before, so please help me to fix that.
Best regards,
PanCave
EDIT:
changing the global.js according to this tutorial (https://www.w3schools.com/php/php_ajax_database.asp) now produces an "no root element found" error :/
$("#submit").click(function () {
var type = $("#type").val();
var tier = $("#tier").val();
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("pkmn-data").innerHTML = this.responseText;
}
};
xmlhttp.open("Get", "pkmn.php?type="+type+"&tier="+tier);
xmlhttp.send();
});
I'm pulling data from Google Calendar events and wanting to display it in my HTML markup. I've got the data being pulled successfully from Google and thought I was passing it into and array the proper way and encoding into JSON. I was also able to make the GET request via JQuery and confirmed it by checking the console to see if it was received. The problem was trying to display it in the HTML markup.
But, after further debugging, it seems my JSON array isn't correct. Almost as if it duplicates itself everytime it looks for more data from Google.
Here is my code:
<?php
header('Content-type: application/json');
error_reporting(E_ALL);
ini_set("display_errors", 1);
include('google-api-php-client-master/autoload.php');
date_default_timezone_set('America/New_York');
//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar");
$client->setDeveloperKey('my_api_key');
$cal = new Google_Service_Calendar($client);
$calendarId = 'my_calendar_id';
//TELL GOOGLE HOW WE WANT THE EVENTS
$params = array(
'singleEvents' => true, //CAN'T USE TIME MIN WITHOUT THIS, IT SAYS TO TREAT RECURRING EVENTS AS SINGLE EVENTS
'orderBy' => 'startTime',
'timeMin' => date(DateTime::ATOM),//ONLY PULL EVENTS STARTING TODAY
);
$events = $cal->events->listEvents($calendarId, $params);
$count = 0;
$items_to_show = 3;
$data = array();
foreach ($events->getItems() as $event)
{
if($count <= $items_to_show)
{
//Convert date to month and day
$eventDateStr = $event->start->dateTime;
if(empty($eventDateStr))
{
// it's an all day event
$eventDateStr = $event->start->date;
}
$temp_timezone = $event->start->timeZone;
if (!empty($temp_timezone))
{
$timezone = new DateTimeZone($temp_timezone); //GET THE TIME ZONE
}
else
{
$timezone = new DateTimeZone("America/New_York"); //Set your default timezone in case your events don't have one
}
if ($count >= $items_to_show)
{
break;
}
$eventdate = new DateTime($eventDateStr,$timezone);
$data[$count]['newmonth'] = $eventdate->format("M");
$data[$count]['newday'] = $eventdate->format("j");
$data[$count]['newtime'] = $eventdate->format("g:i A");
echo json_encode($data);
++$count; //INCREASE COUNT AND START AGAIN.
}
}
?>
Here is my JSON array (there are only 3 events on the calendar) but it looks like it duplicates or resets everytime it looks for more:
[{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"}][{"newmonth":"Jan","newday":"16","newtime":"3:00 PM"},{"newmonth":"Jan","newday":"17","newtime":"2:00 PM"},{"newmonth":"Jan","newday":"18","newtime":"3:00 AM"}]
Here is my JQuery that I want to display in the HTML automatically:
$(document).ready(function()
{
function load()
{
$.ajax
({
type: 'GET',
url: 'googlesidebar.php',
// data: {key: 'value'},
dataType: 'json',
success: function(data)
{
console.debug(data);
for (var i = 0; i < data.length; i++)
{
$('.newmonth').append(data[i].newmonth),
$('.newday').append(data[i].newday),
$('.newtime').append(data[i].newtime)
};
setTimeout(load, 5000);
},
error: function(data)
{
//called when there is an error
console.log(data.message);
}
});
};
load();
});
HTML Markup:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="newmonth"></div>
<div class="newday"></div>
<div class="newtime"></div>
<footer>
</footer>
<script src="ajax.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Any help would be greatly appreciated!