Redraw Chart.js with PHP JSON - javascript

I created a page where there the user selects a business and the page throws a barchart. The problem is that, the first time the use selects a business, the page shows the barchart correctly, but the second time the user selects a business, the page throw two charts with the past and new information. Here is my code.
<!DOCTYPE html>
<html>
<head>
<title>Estadisticas</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<select id="mySelect"></select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<div id="graph-container">
<canvas id="myChart"></canvas>
</div>
</body>
</html>
JAVASCRIPT
$(document).ready(function() {
/*
var numbers = [1, 2, 3, 4, 5];
var values = ["uno","dos","tres","cuatro","cinco"]
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ values[i] + '">' + numbers[i] + '</option>';
}
$('#mySelect').append(option);
*/
$.ajax({
url: "xx",
method: "GET",
success: function(data) {
var values = [];
var business = [];
var option = '';
for (var i in data) {
values.push(data[i].values);
business.push(data[i].Business);
option += '<option value="' + values[i] + '">' + business[i] + '</option>';
}
$('#mySelect').append(option);
},
error: function(data) {
console.log(data);
}
});
function getData(dato) {
$.ajax({
url: "zx",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var views = [];
for (var i in data) {
date.push("Date " + data[i].Date);
views.push(data[i].Views);
}
var chartdata = {
labels: date,
datasets: [{
label: 'Date',
backgroundColor: 'rgba(231,76,60 ,1)',
borderColor: 'rgba(231,76,60 ,1)',
hoverBackgroundColor: 'rgba(52,152,219 ,1)',
hoverBorderColor: 'rgba(52,152,219 ,1)',
data: views
}]
};
var ctx = $("#myChart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
}
$('#mySelect').change(function() {
console.log($(this).find(':selected').text());
console.log($(this).find(':selected').val());
getData($(this).find(':selected').val());
});
});
My webservices work, the only problem is at the moment the user selects another business, the page throws two charts with the past and new information.

You have to create a new dataset and push into the chart

Related

plotly js globals not being available to other function

This is usually a simple problem to solve with a global var. But nooooo...
All the code works, the csv is read in, the arrays created with the correct values (x,y), a default graph is drawn, but the newPlot function vars are not acting like globals and are empty, so the plot is an empty default of 6x6 with no traces. The newPlot vars are globals. Is plotly.js different? Line 63 is the culprit. This code is pretty much a clone of: plotlyHover
<!DOCTYPE html>
<html lang="en" >
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<div id="myDiv"></div>
<div id="hoverinfo" style="margin-left:80px;"></div>
<!-- cloudcover.csv looks like this.
Time,CloudCover
2022-04-06 10:07:09,0
2022-04-06 11:07:18,100.0
2022-04-06 12:08:17,100.0
2022-04-06 13:09:16,96.0
2022-04-06 14:10:15,66.0
2022-04-06 15:11:14,7.0
-->
<script>
var traces = [];
var layout = {};
var config = {};
const CSV = "cloudcover.csv";
Plotly.d3.csv(CSV, function(rows) {
let x = [];
let y = [];
let row;
let i = 0;
while (i < rows.length) {
row = rows[i];
x.push(row["Time"]);
y.push(row["CloudCover"]);
i += 1;
};
traces = [{
x: x,
y: y,
line: {
color: "#387fba"
},
width: 16,
}];
layout = {
title: 'Cloudcover',
yaxis: {
range: [0, 100]
},
xaxis: {
tickformat: "%H:%M:%S"
}
};
config = {
responsive: true
};
});
Plotly.newPlot('myDiv', traces, layout, config, {
showSendToCloud: true
});
var myPlot = document.getElementById('myDiv')
hoverInfo = document.getElementById('hoverinfo')
myPlot.on('plotly_hover', function(data) {
var infotext = data.points.map(function(d) {
return (d.data.name + ': x= ' + d.x + ', y= ' + d.y.toPrecision(3));
});
hoverInfo.innerHTML = infotext.join('<br/>');
})
myPlot.on('plotly_unhover', function(data) {
hoverInfo.innerHTML = '';
});
</script>
</body>
</html>

Javascript readin txt file into chart

I really need some help to figure this out...
I have found a code which plot a chart out of values he gets from a website.
This is close what I would like to achieve.
But I dont want to get the values from the website but from a txt file.
I read that I should use json strings to convert it, but I'm not a programmer so I don't understand how to do such thing.
At the end of my question I have the code that get its value from the internet.
The txt file needs for now to be just easy like:
[[0, 7], [1, 12], [2, 7], [3, 3], [4, 0], [5, 4]]
The code
<!DOCTYPE HTML>
<html>
<head>
<script>
//chart
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
title: {
text: "Live Data"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
updateData();
// Initial Values
var xValue = 0;
var yValue = 10;
var newDataCount = 6;
function addData(data) {
if (newDataCount != 1) {
$.each(data, function(key, value) {
dataPoints.push({
x: value[0],
y: parseInt(value[1])
});
xValue++;
yValue = parseInt(value[1]);
});
} else {
//dataPoints.shift();
dataPoints.push({
x: data[0][0],
y: parseInt(data[0][1])
});
xValue++;
yValue = parseInt(data[0][1]);
}
newDataCount = 1;
chart.render();
setTimeout(updateData, 1500);
}
function updateData() {
$.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=" + xValue + "&ystart=" + yValue + "&length=" + newDataCount + "type=json", addData);
}
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
</body>
</html>
Add the URL for the text file containing the JSON into the updateData function found in your code, replacing "https://www.mywebsite/thetextfile.txt" in the example below with the URL to your text file.
function updateData() {
$.getJSON("https://www.mywebsite/thetextfile.txt", addData);
}

StackOverflow API - Trouble Displaying Results

I am kind of new to API's and I have the hang of some of it, but not quite all of it yet. When I type in a tag, such as "HTML" or "JavaScript", I am trying to write a program that will give me the top answerers for that tag. When I type in my result, it says "20 results for undefined," so for some reason, I don't think my code is "communicating" propertly.
I think it has to do with my "Tagged: answered" part, but I'm not sure. What do you guys think?
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stack Overflow AJAX Demo</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<div class="intro">
<div class="left stack-image"></div>
<div class="explanation">
<h1>StackOverflow Reputation Builder</h1>
<p>This app lets you search by topic for unanswered questions on Stack Overflow to help you build your reputation. Find unanswered questions for a topic you know about, write quality answers, and watch your reputation go up.</p>
<p>Sometimes, you also need some inspiration. This page also lets you search for the top answerers for a tag. If you want to rise to the top ranks for a topic, see how many reputation points you'll need to aim for!</p>
</div>
</div>
<hr>
<div class="stack">
<h3>Get Unanswered Questions</h3>
<p>Find unanswered questions by tag. For multiple tags, use a semi-colon to separate.</p>
<form class="unanswered-getter" onsubmit="return false;">
<input type="text" placeholder='e.g., "HTML" or "HTML;CSS"' name="tags" size="30" autofocus required>
<input type="submit" value="Submit">
</form>
<h3>View the Top Answerers for a Tag</h3>
<form class="inspiration-getter" onsubmit="return false;">
<input type="text" placeholder="e.g., jQuery" name="answerers" size="30" required>
<input type="submit" value="Submit">
</form>
</div>
<div class="results-container">
<div class="search-results"></div>
<div class="results"></div>
</div>
</div>
<div class="templates hidden">
<dl class="result question">
<dt>Question</dt>
<dd class="question-text"></dd>
<dt>Asked</dt>
<dd class="asked-date"></dd>
<dt>Viewed</dt>
<dd class="viewed"></dd>
<dt>Asker</dt>
<dd class="asker"></dd>
</dl>
<dl class="resultAnswerer">
<dt>Name of Answerer:</dt>
<dd class="answererName"></dd>
<dt>Score:</dt>
<dd class="scoreAmount"></dd>
<dt>Reputation:</dt>
<dd class="reputationAmount"></dd>
</dl>
<div class="error">
<p>Uh-oh! Something went wrong with your request. Here's what we know:</p>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Javascript:
var showQuestion = function(question) {
var result = $('.templates .question').clone();
var questionElem = result.find('.question-text a');
questionElem.attr('href', question.link);
questionElem.text(question.title);
var asked = result.find('.asked-date');
var date = new Date(1000*question.creation_date);
asked.text(date.toString());
var viewed = result.find('.viewed');
viewed.text(question.view_count);
var asker = result.find('.asker');
asker.html('<p>Name: <a target="_blank" '+
'href=http://stackoverflow.com/users/' + question.owner.user_id + ' >' +
question.owner.display_name +
'</a>' +
'</p>' +
'<p>Reputation: ' + question.owner.reputation + '</p>'
);
return result;
};
var topScorers = function(score){
var result = $('.templates .resultAnswerer').clone();
var answererDisplayName = result.find('answererName');
answererDisplayName.text(score.display_name);;
var answererScore = result.find('scoreAmount');
answererScore.text(score.score);
var answererReputation = result.find('reputationAmount');
answererReputation.text(score.reputation);
return result;
}
var showSearchResults = function(query, resultNum) {
var results = resultNum + ' results for <strong>' + query + '</strong>';
return results;
};
var showError = function(error){
var errorElem = $('.templates .error').clone();
var errorText = '<p>' + error + '</p>';
errorElem.append(errorText);
};
var getUnanswered = function(tags) {
var request = { tagged: tags,
site: 'stackoverflow',
order: 'desc',
sort: 'creation'};
$.ajax({
url: "http://api.stackexchange.com/2.2/questions/unanswered",
data: request,
dataType: "jsonp",//use jsonp to avoid cross origin issues
type: "GET",
})
.done(function(result){ //this waits for the ajax to return with a succesful promise object
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i, item) {
var question = showQuestion(item);
$('.results').append(question);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
};
var getAnswerers = function(answered){
var request = {
tagged: answered,
site: 'stackoverflow',
order: 'desc',
sort: 'score',
};
$.ajax({
url: "http://api.stackexchange.com/2.2/tags/" + answered + "/top-answerers/all_time",
data: request,
dataType: "jsonp",
type: "GET",
})
.done(function(result){
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i,item){
var score = topScorers(item);
$('.results').append(score);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
}
$(document).ready( function() {
$('.unanswered-getter').submit(function(){
$('.results').html('');
var tags = $(this).find("input[name='tags']").val();
getUnanswered(tags);
});
$('.inspiration-getter').submit(function(){
$('.results').html('');
var answered = $(this).find("input[name='tags']").val();
getAnswerers(answered);
});
});
You're probably calling the getAnswer on submit of a form. Form submission will destroy the Javascript context. To make it work correctly, you should use simple click instead of submit.
Check code below:
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
img {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<input class="tag"/><button class="search">Search</button>
<div class="search-results"></div>
<script>
var topScorers = function(score){
//Clone result template ode
var result = $('.templates .resultAnswerer').clone();
//set the display name in result
var answererDisplayName = result.find('answererName');
answererDisplayName.text(score.display_name);;
//set the user score amount in result
var answererScore = result.find('scoreAmount');
answererScore.text(score.score);
//set the user reputation amount in result
var answererReputation = result.find('reputationAmount');
answererReputation.text(score.reputation);
return result;
}
var getAnswerers = function(answered){
//the parameters I need to pass in our request to StackOverflow's API
var request = {
tagged: answered,
site: 'stackoverflow',
order: 'desc',
sort: 'score',
};
$.ajax({
//the parameters I need to pass in our request to stackOverFlow's API
//this is the endpoint that I want to use
url: "http://api.stackexchange.com/2.2/tags/" + answered + "/top-answerers/all_time",
data: request,
dataType: "jsonp",
type: "GET",
})
//what the function should do if successful
.done(function(result){
//this gives you the search result description
//var searchResults = showSearchResults(request.tagged, result.items.length);
showResults(result.items);
})
//what the function should do if it fails
.fail(function(jqXHR, error){
$('.search-results').text(JSON.stringify(error));
});
}
function showResults (result) {
var tbody = "";
var thead = "";
var firstEl = result[0];
var propArr = [];
for(var prop in firstEl) {
if(typeof firstEl[prop] !== "object") {
thead += "<th>" + prop + "</th>";
propArr.push(prop);
} else {
var obj = firstEl[prop]
for(var propdeep in obj) {
thead += "<th>" + propdeep + "</th>";
propArr.push(propdeep);
}
}
}
result.forEach(function (rowEl) {
var row = "<tr>";
var currentEl = null;
for(var i = 0; i < propArr.length; i++) {
currentEl = rowEl[propArr[i]];
if(currentEl === undefined) {
currentEl = rowEl["user"][propArr[i]]
}
if(propArr[i] !== "profile_image") {
row += "<td>"+ currentEl + "</td>";
} else {
row += "<td><img src='"+ currentEl + "'></img></td>";
}
}
row += "</tr>";
tbody += row;
});
var table = "<table><thead>" + thead + "</thead><tbody>" + tbody + "</tbody></table>";
$('.search-results').html(table);
}
$('.search').click(function(){
//zero out results if previous search has run
$('.search-results').html('');
//separate line of code
var answered = $(".tag").val();
getAnswerers(answered);
});
</script>
</body>
</html>
*Edit***********************
Since you're using "return false;" in submit of the forms, it's not submitting. That's actually clever as it saves us from having to attach both mouse and key events
There were 3 bugs in the code you posted last.
1> Input text field name is "answerers" but in the submit() function it's used as "tags".
var answered = $(this).find("input[name='tags']").val();
// should be
var answered = $(this).find("input[name='answerers']").val();
2> Data returned from the inspiration-getter form call has different structure than used. Actual structure of each item is as below.
{
post_count: 0,
score: 0,
user: {
display_name: "",
link: "",
profile_image: "",
reputation: 0,
user_id: 0,
user_type: ""
}
}
3> There should be a . (dot) before the selectors used in the topScorers() function.
var answererDisplayName = result.find('answererName'); //should be '.answererName'
answererDisplayName.text(score.display_name);;
var answererScore = result.find('scoreAmount'); //should be '.scoreAmount'
answererScore.text(score.score);
var answererReputation = result.find('reputationAmount'); //should be '.reputationAmount'
That's it,
Here is the working code after corrections,
app.js
var showQuestion = function(question) {
var result = $('.templates .question').clone();
var questionElem = result.find('.question-text a');
questionElem.attr('href', question.link);
questionElem.text(question.title);
var asked = result.find('.asked-date');
var date = new Date(1000*question.creation_date);
asked.text(date.toString());
var viewed = result.find('.viewed');
viewed.text(question.view_count);
var asker = result.find('.asker');
asker.html('<p>Name: <a target="_blank" '+
'href=http://stackoverflow.com/users/' + question.owner.user_id + ' >' +
question.owner.display_name +
'</a>' +
'</p>' +
'<p>Reputation: ' + question.owner.reputation + '</p>'
);
return result;
};
var topScorers = function(item){
var user = item.user;
var result = $('.templates .resultAnswerer').clone();
var answererDisplayName = result.find('.answererName');
answererDisplayName.text(user.display_name);;
var answererScore = result.find('.scoreAmount');
answererScore.text(item.score);
var answererReputation = result.find('.reputationAmount');
answererReputation.text(user.reputation);
return result;
}
var showSearchResults = function(query, resultNum) {
var results = resultNum + ' results for <strong>' + query + '</strong>';
return results;
};
var showError = function(error){
var errorElem = $('.templates .error').clone();
var errorText = '<p>' + error + '</p>';
errorElem.append(errorText);
};
var getUnanswered = function(tags) {
var request = { tagged: tags,
site: 'stackoverflow',
order: 'desc',
sort: 'creation'};
$.ajax({
url: "http://api.stackexchange.com/2.2/questions/unanswered",
data: request,
dataType: "jsonp",//use jsonp to avoid cross origin issues
type: "GET",
})
.done(function(result){ //this waits for the ajax to return with a succesful promise object
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i, item) {
var question = showQuestion(item);
$('.results').append(question);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
};
var getAnswerers = function(answered){
var request = {
tagged: answered,
site: 'stackoverflow',
order: 'desc',
sort: 'score',
};
$.ajax({
url: "http://api.stackexchange.com/2.2/tags/" + answered + "/top-answerers/all_time",
data: request,
dataType: "jsonp",
type: "GET",
})
.done(function(result){
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i,item){
var score = topScorers(item);
$('.results').append(score);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
}
$(document).ready( function() {
$('.unanswered-getter').submit(function(){
$('.results').html('');
var tags = $(this).find("input[name='tags']").val();
if(!tags || $.trim(tags) === "") {
alert("input is empty");
} else {
getUnanswered(tags);
}
});
$('.inspiration-getter').submit(function(){
$('.results').html('');
var answered = $(this).find("input[name='answerers']").val();
if(!answered || $.trim(answered) === "") {
alert("input is empty");
} else {
getAnswerers(answered);
}
});
});
I figured out part of what I did wrong.
I had name 'tags" instead of name 'answerers', so part of my problem is fixed.
Now if I get results, it will say "20 results of HTML" or "20 results of CSS" or whatever tag I use.
Now I just need to figure out why all of my results are blank. For some reason, it works for one button, but not the other.
JavaScript:
$('.inspiration-getter').submit(function(){
$('.results').html('');
var answered = $(this).find("input[name='tags']").val();
getAnswerers(answered);
});
HTML:
<form class="inspiration-getter" onsubmit="return false;">
<input type="text" placeholder="e.g., jQuery" name="answerers" size="30" required>
<input type="submit" value="Submit">
</form>

How to transfer Javascript code correctly?

I have two codes, both generate a line chart. However, the first one doesn't use mysql datasource, it uses random math generated datapoints. But it uses a refresh interval and thus is live.
The second code does in fact use a mysql datasource and displays the data in my database in the line-chart. However it is not live, because it does not it has not refresh-interval function.
I was trying to transfer the refresh-Interval / chart-update code parts of the first code to my second code that is not live but uses a real data source.
Here is my live code, with random datapoints:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">`
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer2",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
This is my code of the static line chart (not live) but uses real data source:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">`
</script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
chart.render();
});
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
This is what I have tried so far:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
var dataPoints = [];
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
};
}
if (dataPoints.length > dataLength)
{
dataPoints.shift();
}
chart.render();
)};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
But it keeps saying
Unexpected token ')' at line 42
chart.render();
)};
I am pretty embarrassed but I can't find the solution due to all the bracelets/parenthesizes. I have tried everything. With ) and without } but nothing seems to deliver.
If this is solved, will the chronological positions of the code be alright?
EDIT: FIRST PROBLEM SOLVED, NEW PROBLEM: JS POSITIONING
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
var dataPoints = [];
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
};
}
if (dataPoints.length > dataLength)
{
dataPoints.shift();
}
chart.render();
});
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(updateChart, updateInterval);
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
output:
Can't find variable: updateChart
You used )}; instead of });
also at the end of your JS you used only } instead of });
also call your chart like
setInterval(updateChart, updateInterval);
and make sure your updateInterval is in the right function scope.
Here's how it should approximately look like:
jQuery(function ($) {
function updateChart( result ) { // move it here!!!
$.getJSON("arduino_data.php", function( result ){
var dataPoints = [];
var dataLength = 500; // number of dataPoints visible at any point
var updateInterval = 1000;
var chart = new CanvasJS.Chart("chartContainer",{ // new chart Object
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
if (dataPoints.length > dataLength){
dataPoints.shift();
}
chart.render();
});
}
// First read - Start
updateChart();
// Update chart after specified time.
setInterval(updateChart, updateInterval);
});

Send JS values to xively using XivelyJS

How can I send two Javascript values to a xively feed, One as the ID and one as the value. Current code is. I want to get those values in to a xively feed so I can access them via an arduino with wifi. Unfortunately getting the values directly from the website from JS does not seem straight forward so this is my workaround unless anyone has a better way of accessing this data from an arduino. Using this example for reference execept i want to send the data from website rather than retrieve it. http://xively.github.io/xively-js/tutorial/
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="parse-1.2.16.min.js"></script>
</head>
<body>
<script>
jQuery(function($){
xively.setKey( "APIKEY" );
Parse.initialize("APIKEY", "APIKEY");
var mValue = Parse.Object.extend("mValue");
var queryLngLat = new Parse.Query(mValue);
var classObject = new mValue();
var existingMarkers= [];
var databaseMarkers= [];
var counter = 0;
var div ;
var resultsLength;
setInterval(function update() {
queryLngLat.notEqualTo("longAndLat", null);
queryLngLat.find({
success: function(results) {
console.log("Successfully retrieved " + results.length + " scores.");
for (var j = 0; j < results.length; j++ ) {
databaseMarkers = (results[j].attributes.longAndLat);
resultsLength = results.length;
counter++;
var markerValueRead = results[j].attributes.Val;
CoordsPush = databaseMarkers.substring(1, databaseMarkers.length - 1);
div = document.createElement("div");
div.style.width = "400px;";
div.style.background = "white";
div.style.color = "black";
div.innerHTML = /*"Database LatLng: " + CoordsPush + " Marker Value: " + */markerValueRead;
div.setAttribute("id", CoordsPush);
document.body.appendChild(div);
//alert(div.id);
JSON.stringify(markerValueRead);
xively.setKey("UYby76Zocsur664I6sRd13BXKUKrpM3xDSntN5qB5fvPxMhG");
var feedID = 129375335,
datastreamID = "LatLng";
selector = "50.3754565, -4.14265649999993"
xively.datastream.get(feedID, datastreamID, function(datastream) {
$selector.html( datastream["current_value"] );
xively.datastream.subscribe(feedID, datastreamID, function( even, datastream_updated) {
$(selector).html(datastream_updated["current_value"]);
});
});
//console.log("(" + markers[d].getPosition().d + ", " + markers[d].getPosition().e +")");
console.log("Database LatLng: " + databaseMarkers + " Marker Value: " + markerValueRead);
}
counter = 0;
}
});
document.body.innerHTML = '';
}, 15000);
});
</script>
<script src="http://d23cj0cdvyoxg0.cloudfront.net/xivelyjs-1.0.4.min.js"></script>
</body>
</html>
Here's a simple example of sending a single value to each of two channels ("foo" and "bar") in a feed...
<!DOCTYPE HTML>
<html>
<head>
<title>Xively Test</title>
<script language="JavaScript" type="text/javascript" src="lib/jquery/jquery-1.10.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="lib/xively/xivelyjs-1.0.4.min.js"></script>
<script language="JavaScript" type="text/javascript">
var API_KEY = "YOUR_API_KEY";
var FEED_ID = "YOUR_FEED_ID";
$(document).ready(function() {
// Set your API key first
xively.setKey(API_KEY);
// build the data packet
var timestamp = new Date().toISOString();
var data = { "version" : "1.0.0",
"datastreams" : [
{ "id" : "foo", "datapoints" : [ {"at" : timestamp, "value" : 10} ] },
{ "id" : "bar", "datapoints" : [ {"at" : timestamp, "value" : 20} ] }
]
};
// upload the data
xively.feed.update(FEED_ID, data, function(response) {
if (response.status == "200") {
console.log("Yay, it worked!: " + JSON.stringify(response, null, 3));
}
else {
console.log("Boo, something went wrong!: " + JSON.stringify(response, null, 3));
}
});
});
</script>
</head>
<body>
Look in the console for output.
</body>
</html>

Categories