Solved

How to update a kendo chart?

Posted on 2014-09-22
15
1,304 Views
Last Modified: 2014-10-22
Hello,

Below is a bit of code i wrote earlier (haha Gary) that uses a KendoChart to display a bar chart.

How would i update the chart data if it changed?

Thanks.


 
$("#chart").kendoChart({
      series: [{
          name: "Vanföreställningar",
          data: [3]
      }, {
          name: "Hallucinationer",
          data: [4]
      }, {
          name: "Agitationaggressivitet",
          data: [9]
      }, {
          name: "Depression/dysfori",
          data: [4]
      }, {
          name: "Ångest",
          data: [2]
      }, {
          name: "Eufori/upprymdhet",
          data: [1]
      }, {
          name: "Apati/likgiltighet",
          data: [9]
      }, {
          name: "Hämningslöshet",
          data: [6]
      }, {
          name: "Irritabilitet/labilitet",
          data: [4]
      }, {
          name: "Motorisk av. beteende",
          data: [2]
      }, {
          name: "Sömn",
          data: [4]
      }, {
          name: "Aptit/ätstörningar",
          data: [12]
      }],
      seriesColors: ["STEELBLUE", "FIREBRICK", "GOLD", "LIGHTBLUE", "INDIANRED", "DIMGREY", "MEDIUMBLUE", "POWDERBLUE", "GREY", "MEDIUMVIOLETRED", "GREEN", "SKYBLUE"],
      legend: {
          position: "bottom"
      }
  });

Open in new window

0
Comment
Question by:soozh
  • 8
  • 4
  • 2
  • +1
15 Comments
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40337884
Do you mean you want to get updated data from a server? As you would use ajax for that
0
 
LVL 58

Expert Comment

by:Gary
ID: 40337920
Just rebind the the full chart again - normally you would use datasource but since that isn't working with seriescolor and the legend it's the only thing you can do.
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40338113
Here is an example of using an external data source: http://jsbin.com/nekir/1/edit?js,output getting data from http://jsbin.com/nehif/1.json (notice how the objects identifiers are enclosed in double quotes)

$(function() {
	$.getJSON("//jsbin.com/nehif/1.json", function(data) {

		$("#chart").kendoChart({
			series: data.series,
			seriesColors: data.seriesColors,
			legend: {
				position: "bottom"
			}
		});
	});
});

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points
ID: 40338183
This produces something fairly reasonable.  I do not have the CSS and I redacted the full example to produce a smaller test data set, but it shows the client/server interaction with the AJAX request.
http://iconoun.com/demo/temp_soozh.php

Client-side script.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://cdn.kendostatic.com/2014.2.903/js/kendo.all.min.js"></script>
<script>

$(document).ready(function(){
    $("#signal").click(function(){
        $.getJSON("temp_soozh_server.php", function(response){
            $("#chart").kendoChart(response);
        });
    });
});
</script>

<title>HTML5 Page With jQuery and Kendo Chart</title>
</head>
<body>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<div id="chart"></div>
<div id="signal">Create Chart</div>

</body>
</html>

Open in new window

Server-side script:
<?php // demo/temp_soozh_server.php
error_reporting(E_ALL);

// TO SIMULATE A DATABASE LOOKUP AND CAUSE A CHANGE OF VALUES ON EACH PAGE LOAD
$a = rand( 1, 3);
$b = rand( 4, 6);
$c = rand( 7, 9);
$d = rand(10,12);

// CREATE AN ARRAY OF OBJECTS
$objects = array
( (object)array("name" => "Vanföreställningar",       "data" => "[$a]")
, (object)array("name" => "Hallucinationer",          "data" => "[$b]")
, (object)array("name" => "Agitationaggressivitet",   "data" => "[$c]")
, (object)array("name" => "Aptit/ätstörningar",       "data" => "[$d]")
)
;

// THE COLORS, RANDOMIZED TO SIMULATE A CHANGE
$seriesColors= array("STEELBLUE", "FIREBRICK", "GOLD", "GREEN");
shuffle($seriesColors);

// THIS SEEMS TO BE AN OBJECT
$legend = new StdClass;
$legend->position = "bottom";

$arr = array
( 'series'       => $objects
, 'seriesColors' => $seriesColors
, 'legend'       => $legend
)
;

// SEND THE JSON STRING
$str = json_encode($arr);
echo $str;

Open in new window

Best to all, ~Ray
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40338290
http://jsbin.com/nekir/2/edit?js,output (click the "refresh" button)

i just destroy the chart and re-create it. seems the easiest way to refresh the data

$(function() {
	$.getJSON("//jsbin.com/nehif/1.json", function(data) {

		$("#chart").kendoChart({
			series: data.series,
			seriesColors: data.seriesColors,
			legend: {
				position: "bottom"
			}
		});
	});
});

function RefreshData() {
	$.getJSON("//jsbin.com/dikufu/1.json", function(data) {
		var chart = $("#chart").data("kendoChart");
		chart.destroy();
		$("#chart").kendoChart({
			series: data.series,
			seriesColors: data.seriesColors,
			legend: {
				position: "bottom"
			}
		});

	});
}

Open in new window


@Ray - Not sure why you repeated what I have already stated.  AND There's no PHP here...
0
 

Author Comment

by:soozh
ID: 40338467
Hej,

Thanks for all the help guys.  I guess i should give you a little more information and background.

I am working in a platform that allows me to render JS code that is run onload, and i can add JS code to object events such as  onclick, onchange etc.

So i dont have full control over all the code generated, how or where it is placed.  Neither am i an expert in JS, Kendom or JSON.

I am trying to add a chart to my application witin the bounds of what the platform will allow.

So when the web page is rendered i generate the code to produce the chart based on the data held in the underlying database.

Then as the user makes changes to this data (its the 12 measurements in the bar chart) I want to update the bar chart with the new value, before the user commits and saves the data.

In my limited view i imagined that i could create the chart, and then as data what changed i would just update the datasource with the new value and force the chart to be redrawn.  I am looking for a solution that requires the minumum amount of processing.

Does this sound like a good solution, and can i use the example given above?  The only problem is dont know how to create the JSON datasource in JS. (i am an old delphi programmer).

So assuming the above is ok, can someone just show me how i can join up the dots... so when there is an onchange in an edit field, i take that value, and update the chart.
0
 
LVL 42

Accepted Solution

by:
Rob Jurd, EE MVE earned 350 total points
ID: 40338704
here ya go: http://jsbin.com/nekir/2/edit?js,output

happy to answer any questions regarding the implementation

This dynamically adds each input box for editing:

		$.each(data.series, function(i,el) {
			var tmp = $('<input/>').attr({
				type: 'text',
				id: 'series'+i,
				name: el.name,
				value: el.data[0]
			});
			tmp.on('change',function() {
				console.log(this.value);
				var chart = $("#chart").data("kendoChart");
					chart.options.series[i].data[0]=this.value;
					chart.refresh();
			});
			$("#container").append(tmp);
		});

Open in new window

0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:soozh
ID: 40338776
Hello,

When i click on the link i can see how it works... but since this is really not my domain i can not work out how.

I guess there must be some code which i have not found that links the onchange events to the update of the chart.

Maybe i will need someone who understands json and jquery to help me out.
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40338804
tmp.on('change',function() {
				//get a reference to the chart
				var chart = $("#chart").data("kendoChart");
				//access the series value for this dimension
chart.options.series[i].data[0]=this.value;
// refresh the chart
					chart.refresh();
			});

Open in new window


Referring to my comment above and this one, please state what you don't understand as I'm more than happy to explain
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40339008
You may also want to open other questions addressing certain aspects of the code I've posted.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40339052
Maybe i will need someone who understands json and jquery to help me out.
Yes, I think that's smart.  You probably want to hire a professional to help you isolate the parts of the question into "bite-sized" portions.  There are a lot of moving parts here and they interact in complex and intricate ways.  My guess is that it will take you at least weeks if not months to go from "not an expert" to "working application" if you rely on trial and error.  So my recommendation would be to get some hands-on help to deconstruct the problem.  And, of course, post questions here at E-E!
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40339059
I agree with Ray.  I started typing out a line by line explanation and there is just far too much information to impart to you.  Which is why I suggest breaking down the parts you don't understand and focusing on those elements until you do.
0
 

Author Comment

by:soozh
ID: 40376869
I have not abandoned this question - just been working on something else - so i will come back to it in a few Days.
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40383595
No problem - I'm still monitoring
0
 

Author Closing Comment

by:soozh
ID: 40396344
We liked the way bob updated the table by just changing the one data value and using refresh.

The only problem we have now is that the diagram changes size on the refresh.  Maybe thats another question?
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Using Quotation Marks in PHP This question (http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28217211.html) seems to come up a lot for developers who are new to PHP.  And it got me thinking, "How can we explain the rule…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video teaches users how to migrate an existing Wordpress website to a new domain.
Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now