I can add guides (vertical lines) to my amchart this way:
var guide1 = new AmCharts.Guide();
guide1.date = new Date(2014, 5, 27);
guide1.lineColor = "#CC0000";
guide1.lineAlpha = 1;
guide1.dashLength = 2;
guide1.inside = true;
guide1.labelRotation = 90;
guide1.label = "Guide label";
stockPanel.categoryAxis.addGuide(guide1);
How could I add a number of these guides dynamically from a list of dates in a database?
Would I be able to generate each one with PHP and include them in my script?
Sample PHP (echoGuide.php):
<?php
$js = <<<JS
var guide1 = new AmCharts.Guide();
guide1.date = new Date(2014, 5, 27);
guide1.lineColor = "#CC0000";
guide1.lineAlpha = 1;
guide1.dashLength = 2;
guide1.inside = true;
guide1.labelRotation = 90;
guide1.label = "Guide label";
JS;
header("Content-type: text/javascript");
echo $js;
exit();
?>
Sample JS in HTML file:
var guide = AmCharts.loadJSON('echoGuide.php');
stockPanel.categoryAxis.addGuide(guide);
AmCharts.loadJSON:
AmCharts.loadJSON = function(url) {
// create the request
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load it
// the last "false" parameter ensures that our code will wait before the
// data is loaded
request.open('GET', url, false);
request.send();
// parse and return the output
return eval(request.responseText);
};
Found a solution:
gDates = AmCharts.loadJSON('db/fetchgDates.php');
for (var key_2 in gDates) {
var obj_2 = gDates[key_2];
var date_2_temp = new Date(obj_2['date']);
var guide = new AmCharts.Guide();
guide.date = date_2_temp;
guide.lineColor = "#CC0000";
guide.lineAlpha = 1;
guide.dashLength = 2;
guide.inside = true;
guide.labelRotation = 90;
guide.label = "test";
stockPanel.categoryAxis.addGuide(guide);
}
Related
I am trying to convert a Three STL viewer demonstration into an ES6 Class which is then compiled with webpack 2 but i want it to open the file from URL rather than from an actual file input, ive managed to load the three components and most of the class is working but i think i am having problems in the scope with a few of the components, ive ran into a problem i dont seem to be able to get past when trying to use FileReader and then opening the scene and object. TypeError: Cannot read property 'remove' of undefined
threeDimensionalModels.js
// jshint esversion:6
import {
Scene, PerspectiveCamera, WebGLRenderer, Geometry, Mesh,
AmbientLight, DirectionalLight, MeshPhongMaterial, Vector3, Face3,
} from 'three';
var thisClass = null;
class threeDimensionalModels {
constructor(height,width,selector){
this.w = height;
this.h = width;
this.selector = selector;
this.renderer = new WebGLRenderer();
this.view = document.getElementById(this.selector);
this.camera = new PerspectiveCamera(45, this.w / this.h, 1, 1000);
this.scene = new Scene();
this.light1 = new DirectionalLight(0xffffff);
this.light2 = new DirectionalLight(0xffffff);
this.mat = new MeshPhongMaterial({ color: 0x339900, specular: 0x030303 });
this.obj = new Mesh(new Geometry(), this.mat);
this.renderer.setSize(this.w, this.h);
this.view.appendChild(this.renderer.domElement);
this.camera.position.set(0, 0, 50);
this.scene.add(new AmbientLight(0x666666));
this.light1.position.set(0, 100, 100);
this.scene.add(this.light1);
this.light2.position.set(0, -100, -100);
this.scene.add(this.light2);
this.scene.add(this.obj);
}
static binaryVector3(view, offset) {
var v = new Vector3();
v.x = view.getFloat32(offset + 0, true);
v.y = view.getFloat32(offset + 4, true);
v.z = view.getFloat32(offset + 8, true);
return v;
}
static loadBinaryStl(buffer) {
// binary STL
var view = new DataView(buffer);
var size = view.getUint32(80, true);
var geom = new Geometry();
var offset = 84;
for (var i = 0; i < size; i++) {
var normal = threeDimensionalModels.binaryVector3(view, offset);
geom.vertices.push(threeDimensionalModels.binaryVector3(view, offset + 12));
geom.vertices.push(threeDimensionalModels.binaryVector3(view, offset + 24));
geom.vertices.push(threeDimensionalModels.binaryVector3(view, offset + 36));
geom.faces.push(
new Face3(i * 3, i * 3 + 1, i * 3 + 2, normal));
offset += 4 * 3 * 4 + 2;
}
return geom;
}
static m2vec3(match) {
var v = new Vector3();
v.x = parseFloat(match[1]);
v.y = parseFloat(match[2]);
v.z = parseFloat(match[3]);
return v;
}
static toLines(array) {
var lines = [];
var h = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === 10) {
var line = String.fromCharCode.apply(
null, array.subarray(h, i));
lines.push(line);
h = i + 1;
}
}
lines.push(String.fromCharCode.apply(null, array.subarray(h)));
return lines;
}
static loadTextStl(buffer) {
var lines = threeDimensionalModels.toLines(new Uint8Array(buffer));
var index = 0;
var scan = function (regexp) {
while (lines[index].match(/^\s*$/)) index++;
var r = lines[index].match(regexp);
return r;
};
var scanOk = function (regexp) {
var r = scan(regexp);
if (!r) throw new Error(
"not text stl: " + regexp.toString() +
"=> (line " + (index - 1) + ")" +
"[" + lines[index-1] + "]");
index++;
return r;
};
var facetReg = /^\s*facet\s+normal\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/;
var vertexReg = /^\s*vertex\s+([^s]+)\s+([^\s]+)\s+([^\s]+)/;
var geom = new Geometry();
scanOk(/^\s*solid\s(.*)/);
while (!scan(/^\s*endsolid/)) {
var normal = scanOk(facetReg);
scanOk(/^\s*outer\s+loop/);
var v1 = scanOk(vertexReg);
var v2 = scanOk(vertexReg);
var v3 = scanOk(vertexReg);
scanOk(/\s*endloop/);
scanOk(/\s*endfacet/);
var base = geom.vertices.length;
geom.vertices.push(threeDimensionalModels.m2vec3(v1));
geom.vertices.push(threeDimensionalModels.m2vec3(v2));
geom.vertices.push(threeDimensionalModels.m2vec3(v3));
geom.faces.push(
new Face3(base, base + 1, base + 2, threeDimensionalModels.m2vec3(normal)));
}
return geom;
}
static loadStlModel(buffer) {
try {
return threeDimensionalModels.loadTextStl(buffer);
} catch (ex) {
return threeDimensionalModels.loadBinaryStl(buffer);
}
}
openStl(url) {
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function() {
blob = xhr.response;
thisClass = this;
var reader = new FileReader();
reader.addEventListener("load", function (ev) {
var buffer = ev.target.result;
var geom = threeDimensionalModels.loadStlModel(buffer);
threeDimensionalModels.scene.remove(thisClass.obj);
threeDimensionalModels.obj = new Mesh(geom, threeDimensionalModels.mat);
threeDimensionalModels.scene.add(threeDimensionalModels.obj);
}, false);
reader.readAsArrayBuffer(blob);
};
xhr.send();
}
}
export default threeDimensionalModels;
HTML
<div id="threedm-view"></div>
<script type="text/javascript">
window.addEventListener("load", function () {
"use strict";
var threedm = new threeDimensionalModels(800,800,'threedm-view');
var loop = function loop() {
requestAnimationFrame(loop);
threedm.obj.rotation.z += 0.05;
threedm.renderer.clear();
threedm.renderer.render(threedm.scene, threedm.camera);
};
loop();
threedm.openStl("/app/uploads/2017/07/Stator.stl");
});
</script>
after a bit more playing around, and looking at the problem area, i realised that i was applying this to the global variable where this in the context i wanted did not exist, i would like to find a better way of passing this into child functions inside ECMA class functions without using a global variable
update
class threeDimensionalModels {
// .... //
openStl(url) {
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
thisClass = this; // Moved from inside xhr.onload
xhr.onload = function() {
blob = xhr.response;
var reader = new FileReader();
reader.addEventListener("load", function (ev) {
var buffer = ev.target.result;
var geom = threeDimensionalModels.loadStlModel(buffer);
thisClass.scene.remove(thisClass.obj);
thisClass.obj = new Mesh(geom, thisClass.mat);
thisClass.scene.add(thisClass.obj);
}, false);
reader.readAsArrayBuffer(blob);
};
xhr.send();
}
// ... //
}
I've got a chart that needs to be manipulated with data from the database. Therefore I have converted the data from the database to JSON string. the problem is that I don't know how to integrate the JSON data I received right into the chart.
These are the files needed to make this work:
The php & PDO query:
<?php
/*host = 'localhost' Namecheap default. Could also use 127.0.0.1 */
try {
$connection= new PDO('mysql:host=localhost;dbname=clicrckc_andfit','clicrckc_osherdo','3563077');
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql="SELECT answer_vegitable,answer_cigarettes,answer_workout FROM answers where user_id=58";
$row=$connection->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
$main = array('data'=>$result,'value'=>array("bgcolor"=>"#f1fff1","message"=>"All records displayed"));
echo json_encode($main);
$connection = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
The HTML & JS needed for chart creation and manipluation:
<title>Statistics Chart</title>
<script src="../amcharts_3.13.1.free/amcharts/amcharts.js" type="text/javascript"></script>
<script src="../amcharts_3.13.1.free/amcharts/serial.js" type="text/javascript"></script>
<script type="text/javascript">
AmCharts.loadJSON = function("barClustered.php") {
// create the request
if (window.XMLHttpRequest) { // XMLHttpRequest object is the keystone of AJAX, and it is used to exchange small
//amounts of data with the server.
// IE7+, Firefox, Chrome, Opera, Safari (modern browsers).
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load it
// the last "false" parameter ensures that our code will wait before the
// data is loaded
request.open('GET',"barClustered.php", false); //Type of request,The acutal URL, asynchronously or not?
request.send(); // Send request to the server.
// Adding code after the send method in case of synchronous request (like the one above).
// parse and return the output
return eval(request.responseText); // responseText is getting the response data as a string.
};
</script>
<!-- The chart code -->
<script>
var chart;
var chartData = [
{
"questions": "Vegtables Eaten",
"This Week": 30.1,
"Last Week": 23.9,
"2 Weeks Ago": 27.5
},
{
"questions": "Workout (Minutes)",
"This Week": 29.5,
"Last Week": 25.1,
"2 Weeks Ago": 26.4
},
{
"questions": "Cigarettes smoked",
"This Week": 24.6,
"Last Week": 25,
"2 Weeks Ago": 28
}
];
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "questions";
chart.startDuration = 1;
chart.plotAreaBorderColor = "#DADADA";
chart.plotAreaBorderAlpha = 1;
// this single line makes the chart a bar chart
chart.rotate = true;
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.gridPosition = "start";
categoryAxis.gridAlpha = 0.1;
categoryAxis.axisAlpha = 0;
// Value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0;
valueAxis.gridAlpha = 0.1;
valueAxis.position = "top";
chart.addValueAxis(valueAxis);
// GRAPHS
// first graph
var graph1 = new AmCharts.AmGraph();
graph1.type = "column";
graph1.title = "This Week";
graph1.valueField = "This Week";
graph1.balloonText = "This Week:[[value]]";
graph1.lineAlpha = 0;
graph1.fillColors = "#ADD981";
graph1.fillAlphas = 1;
chart.addGraph(graph1);
// second graph
var graph2 = new AmCharts.AmGraph();
graph2.type = "column";
graph2.title = "Last Week";
graph2.valueField = "Last Week";
graph2.balloonText = "Last Week:[[value]]";
graph2.lineAlpha = 0;
graph2.fillColors = "#81acd9";
graph2.fillAlphas = 1;
chart.addGraph(graph2);
// Third graph
var graph3 = new AmCharts.AmGraph();
graph3.type = "column";
graph3.title = "2 Weeks Ago";
graph3.valueField = "2 Weeks Ago";
graph3.balloonText = "2 Weeks Ago:[[value]]";
graph3.lineAlpha = 0;
graph3.fillColors = "#9972C1";
graph3.fillAlphas = 1;
chart.addGraph(graph3);
// LEGEND
var legend = new AmCharts.AmLegend();
chart.addLegend(legend);
chart.creditsPosition = "top-right";
// WRITE
chart.write("chartdiv");
});
</script>
<script src="http://www.click-and-fit.me/amcharts_3.13.1.free/amcharts/serial.js"></script>
<script src="http://click-and-fit.me/amcharts_3.13.1.free/amcharts/amcharts.js"></script>
<body>
<div id="chartdiv" style="width:500px; height:600px;"></div>
</body>
These are the 2 files above in action:
http://click-and-fit.me/barClustered.php
Statistics Chart
Here's a screenshot of the 3 rows from the database I would like to show in the chart:
http://www.codingforums.com/redirect-to/?redirect=http%3A%2F%2Fimgbox.com%2FHfD1PuTQ
Currently the chart is filled with manually inputted data in a JSON format. How do I get the JSON string from the php file to be manipluated within the cart data? tried to look all over amcharts documentation and could not still understand how to do it.
Thanks in advance!
Try the following:
Change
AmCharts.loadJSON = function("barClustered.php") {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', "barClustered.php", false);
request.send();
return eval(request.responseText);
};
to
AmCharts.loadJSON = function(url) {
if (window.XMLHttpRequest) {
var request = new XMLHttpRequest();
} else {
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', url, false);
request.send();
return eval(request.responseText);
};
Change
chart.dataProvider = chartData;
to
chart.dataProvider = AmCharts.loadJSON('http://click-and-fit.me/barClustered.php');
Im new to XSLT. I am getting a XML file from return value of ECHO from PHP.
Then I try to transform to XSL but it only works in Firefox.
When I run the Javascript debugger from Chrome it says
:
Uncaught TypeError: undefined is not a function maintenance.js:30
getData
[Added: the OP eventually noted that line 30 of maintenance.js reads:
function generateReport() {
xHRObject.open("GET", "getXML.php", rue);
xHRObject.onreadystatechange = getData; //this is where i get debug error in chrome
xHRObject.send(null);
}
I have broken this into multiple lines for legibility.]
But when I run firebug with same code in Firefox no error and can get the result I want.
var xhr = false;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xhr.readyState == 4) &&(xhr.status == 200))
{
if (window.ActiveXObject)
{
var xml = xhr.responseXML;
var xsl = new ActiveXObject("Microsoft.XMLDOM");
xsl.async = false; xsl.load("abc.xsl");
var transform = xml.transformNode(xsl);
var frame = document.getElementById("frame");
frame.innerHTML = transform;
}
else
{
var xsltProcessor = new XSLTProcessor();
xslStylesheet = document.implementation.createDocument("", "doc", null);
xslStylesheet.async = false;
xslStylesheet.load("abc.xsl");
xsltProcessor.importStylesheet(xslStylesheet);
xmlDoc = xhr.responseXML;
var fragment = xsltProcessor.transformToFragment(xmlDoc, document);
document.getElementById("frame").innerHTML = new XMLSerializer().serializeToString(fragment);
}
}
}
function test()
{
xhr.open("GET", "getXML.php", true);
xhr.onreadystatechange = data;
xhr.send(null);
}
I have 3 Javascript functions called from the body onload in the HTML page.
Each Javascript function is contained in it's own Javascript file. Each Javascript file corresponds to another CGI script on the server.
The bodyonload.js looks like:
function bodyOnload() {
getElementsA();
getElementsB();
getElementsC();
}
Each getElements function simply calls a CGI script to get the contents for 3 different selectboxes.
The problem is that as all 3 functions are called asynchronously the select boxes are getting the wrong results. It's almost like the 3 functions are stepping on each other and putting the CGI responses in the wrong selectbox. I know the CGI responses are correct. This works fine if I serially call each function from the others. Like calling the 2nd function from the first and the 3rd function from the second. The asynchronous nature of them running at the same time seems to cause the problem.
This is the general code for each javascript file that contains the getElements functions.
function getElementsA() {
strURL = "http://test.com/scriptA.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxA(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxA(str)
{
document.getElementById("selectBoxA").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxA");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
-------------------
function getElementsB() {
strURL = "http://test.com/scriptB.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form- urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxB(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxB(str)
{
document.getElementById("selectBoxB").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxB");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
------------------------
function getElementsC() {
strURL = "http://test.com/scriptC.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxC(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxC(str)
{
document.getElementById("selectBoxC").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxC");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
It's almost like the 3 functions are stepping on each other
That's exactly what's happening, you're overwriting the onreadystatechange handler set on getElementsA when you call getElementsB, and then again when you call getElementsC. That's because this and self are the global object in all three functions (assuming they're all similar to getElementsA).
You can circumvent that by changing your function calls to object instantiation:
function bodyOnload() {
new getElementsA();
new getElementsB();
new getElementsC();
}
Sorry for that stupid question but, is this code right because it seems to be broken.
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var nocache = 0;
function vloz() {
var kom= encodeURI(document.getElementById('komen').value);
var site_name = encodeURI(document.getElementById('user_id').value);
var p_id = encodeURI(document.getElementById('p_id').value);
var zed = encodeURI(document.getElementById('zed').value);
nocache = Math.random();
http.open('get', 'kmnt.php?site_url='+kom+'&site_name=' +site_name+'&site='+p_id+'& zed='+zed+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
}
}
I have a form when i am sending komen, user_id, p_id and zed
Not sure if this is it but it appears that you have one too many curly braces in the beginning of your code:
if(browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
// } <- extra one here