new containerTable is created every time Google Chart is redrawn - javascript

I have a submit button that submits the date/time period for Annotation Chart in Google Charts.
When I click the button, it redraws the chart with new query result.
It redraws the chart, but every time it does that, it also generates a trailing, empty container as in the screenshot below.
https://www.dropbox.com/s/7fyiy6pxlxkmeik/Screen%20Shot%202014-05-01%20at%2011.58.59%20AM.png
If you see the screenshot, you can see there is two chart_div2_AnnotationChart_containerTable.
I can't simply ignore this new containerTable or delete it, because it contains the buttons and annotations for the refreshed chart.
How can I fix this?
When I redraw the chart, I am calling the function below with new query result.
function drawChart(myData, id) {
var data = new google.visualization.DataTable();
var params = myData[0];
for(var i = 0; i < params.length; i++) {
data.addColumn(params[i][0], params[i][1]); //type and name pair
}
var q_result = myData[1];
var rows = new Array(q_result.length);
for(var i = 0; i < q_result.length; i++) {
tmp_array = [];
for(var j = 0; j < q_result[0].length; j++) {
var tobeadded = params[j][0]=='date'?
new Date(q_result[i][j]) : q_result[i][j];
tmp_array.push(tobeadded);
}
rows[i] = tmp_array;
}
data.addRows(rows);
var chart = new google.visualization.AnnotationChart(
document.getElementById('chart_div'+id));
var options = {
displayAnnotations: true,
};
chart.draw(data, options);
}
When the chart is redrawn, drawChart() is called in the function below.
function g(idx, start, end) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", '/${conf["name"]}/submit_data?idx=' + idx + '&start=' + start + '&end=' + end, true);
xmlhttp.onreadystatechange = function(i) {
return function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
drawChart(JSON.parse(xmlhttp.responseText), i);
}
};
}(idx);
xmlhttp.send();
}
When the chart is initially drawn, it is called from the function below.
function getData() {
// code for IE7+, Firefox, Chrome, Opera, Safari
xhrs = [];
if(window.XMLHttpRequest) {
for (var i = 0; i < ${size}; ++i) {
xhrs.push(new XMLHttpRequest());
}
}
else { // code for IE6, IE5
for (var i = 0; i < ${size}; ++i) {
xhrs.push(new ActiveXObject("Microsoft.XMLHTTP"));
}
}
for (var i = 0; i < ${size}; ++i) {
xhrs[i].open("GET", '/${conf["name"]}/submit_data?idx=' + i, true);
xhrs[i].onreadystatechange = function(idx) {
return function() {
if(xhrs[idx].readyState == 4 && xhrs[idx].status == 200) {
drawChart(JSON.parse(xhrs[idx].responseText), idx);
}
};
}(i);
xhrs[i].send();
}
}

Here's some example code that reuses chart objects instead of recreating them:
function drawCharts () {
var data = [], charts = [], xhrs = [], options = {
displayAnnotations: true
};
for (var i = 0; i < ${size}; ++i) {
if(window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xhrs.push(new XMLHttpRequest());
}
else {
// code for IE6, IE5
// you probably want to throw an error here, since the visualization API does not support IE 5, 6 anyway
xhrs.push(new ActiveXObject("Microsoft.XMLHTTP"));
}
charts.push(new google.visualization.AnnotationChart(document.getElementById('chart_div'+id));
xhrs[i].open("GET", '/${conf["name"]}/submit_data?idx=' + i, true);
xhrs[i].onreadystatechange = function(idx) {
return function() {
if(xhrs[idx].readyState == 4 && xhrs[idx].status == 200) {
var myData = JSON.parse(xhrs[idx].responseText);
data[idx] = new google.visualization.DataTable();
var params = myData[0];
for(var i = 0; i < params.length; i++) {
data[idx].addColumn(params[i][0], params[i][1]); //type and name pair
}
var q_result = myData[1];
var rows = new Array(q_result.length);
for(var i = 0; i < q_result.length; i++) {
tmp_array = [];
for(var j = 0; j < q_result[0].length; j++) {
var tobeadded = params[j][0]=='date' ? new Date(q_result[i][j]) : q_result[i][j];
tmp_array.push(tobeadded);
}
rows[i] = tmp_array;
}
data[idx].addRows(rows);
charts[idx].draw(data[idx], options);
}
};
}(i);
xhrs[i].send();
}
}

Related

Javascript and json pharse loop with external file

I should loop this json file to javascript, all the entries are important and must be retrieved.
I need to make this json compatible with this javascript code.
This is my json file:
{ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
This is my code javascript:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
var user_token = arr[0].user_token;
for(i = 0; i < arr.length; i++) {
var level = arr[i].level;
out += user_token;
}
document.getElementById("id01").innerHTML = out;
}
var jsonInput={ "user_token":"6664e310e87f75ad4fd5674a976f8310", "lesson_language":"it_de", "language_app":"it", "main_levels":[ { "level":"1_it_de" }, { "level":"5_it_de" } ] }
function myFunction(arr) {
var out = "";
var i;
var userLabel=''
var user_token = arr.user_token;
mainArrObj=arr.main_levels
for(i = 0; i < mainArrObj.length; i++) {
var level = mainArrObj[i].level;
out += user_token + ' ';
userLabel += level + ' ';
}
console.log('user_token :'+out);
console.log('userLabel :'+userLabel);
}
myFunction(jsonInput)

Cannot read property 'getElementsByTagName' of null. Cannot figure it out

I have the following code. It seems to work fine in Firefox but I get the uncaught type error in Chrome. What am I missing?
$(document).ready(function() {
$('#btn').click(function() {
var request = new XMLHttpRequest();
let url = `https://comicvine.gamespot.com/api/characters/?api_key=[apikey]`;
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var response = JSON.parse(this.responseText);
getElements(response);
}
}
request.open("GET", url, true);
request.overrideMimeType('text/xml');
request.send();
alert(request.status);
alert(request.statusText);
var xml = request.responseXML;
var table;
var users = xml.getElementsByTagName("character");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var names = user.getElementsByTagName("name");
var name= user.getElementsByTagName("real_name");
for (var j = 0; j < names.length; j++) {
alert(names[j].childNodes[0].nodeValue);
}
}
document.getElementById("results").innerHTML = table;
});
});
I can view the data in Firefox, however nothing is displayed in Chrome.
You are attempting to get the response before it is given. I would use jQuery's ajax to complete the call.
$.ajax({
url: url,
type: "GET",
headers: {
"Accept": "application/xml;"
},
success: function(data, textStatus, xhr) {
alert(textStatus);
var xml = data;
var table;
var users = xml.getElementsByTagName("character");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var names = user.getElementsByTagName("name");
var name = user.getElementsByTagName("real_name")
for (var j = 0; j < names.length; j++) {
alert(names[j].childNodes[0].nodeValue);
}
}
document.getElementById("results").innerHTML = table;
},
error: function(data, textStatus, xhr) {
alert("error occured\n" data.message);
}
});

How to print xmlhttp response?

I am getting some information from database, this information is getting back into JSON format now I need to print this JSON information. But my code is not working getCountryDetails.php is php file for interacting with the database. Following code is the script, When I click the button It intersects with database.
<script type="text/javascript">
$(document).ready(function() {
$("#quickSearch").click(function(){
var countries = [];
$.each($("#select-choice-1 option:selected"), function(){
countries.push($(this).val());
});
if (countries == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//myFunction(xmlhttp.responseText);
myFunction(xmlhttp.responseText);
}
}
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET","webservices/getCountryDetails.php?q="+countries,true);
xmlhttp.send();
}
});
});
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
Firstly, countries will never be an empty string, you've defined it as an array
var countries = [];
...
if (countries == "") { // always fail
secondly, you can't concantenate an array into a string, and XMLHttpRequest doesn't accept arrays
xmlhttp.open("GET","webservices/getCountryDetails.php?q=" + countries, true);
Thirdly, you seem to be using jQuery, so why not use it as it does accept an array
$.ajax({
url : 'webservices/getCountryDetails.php',
data : countries
}).done(myFunction);

Ajax - For loop

Ajax calls an array of four strings, I then want to print each string to a new line.
I have this code:
window.onload = function () {
var obj;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj = JSON.parse(xmlhttp.responseText);
for (var i = 0; i <= obj.length; i++) {
document.createTextNode(obj[i]);
}
}
}
xmlhttp.open("GET", "verify.php", true);
xmlhttp.send();
}
However, it doesn't work. obj.length returns 4, I don't know whether the loop isn't executing, or if I can't access the DOM? I'm very new to Javascript and DOM scripting.
Thanks in advance.
You need to actually put the nodes into the document.
var node;
for (var i = 0, n = obj.length; i < n; i++) { // NB: not <=
node = document.createTextNode(obj[i]);
document.body.appendChild(node);
node = document.createElement('br');
document.body.appendChild(node);
}
This only creates the textNode, you must still apply it to the DOM somehwere via appendChild:
https://developer.mozilla.org/en/DOM/document.createTextNode

How do I read XML in JavaScript?

Alright, so I got this xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<level>
<tiles>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1111111111111111</row>
</tiles>
</level>
and I got my XML reading code:
var xmlDoc = document.implementation.createDocument("","",null);
and
function loadXML(){
xmlDoc.load("levels/test.xml");
xmlDoc.onload = readLevel();
}
function readLevel() {
throw(xmlDoc);
if(xmlDoc.getElementsByTagName("tiles")[0].hasChildNodes()){
var rowNum = xmlDoc.getElementsByTagName("tiles").getChildNodes();
level = [];
for(var i = 0; i < rowNum; i++){
level[i] = [];
var tempStr = xmlDoc.getElementsByTagName("tiles").childNodes[i].textContent;
for(var j = 0; j < 16; j++){
level[i][j] = parceInt(tempStr.charAt(j));
}
}
}
for (var i = 0; i < level.length; i++) {
blockArray[i] = []; // Create the second level for this index
for (var j = 0; j < level[i].length; j++) {
var tempImg = new Image();
tempImg.src = "images/block" + level[i][j] + ".png";
blockArray[i][j] = new block(j * blockSize, i * blockSize, level[i][j], false, false, tempImg);
//throw('blockArray['+i+']'+j+'] = ' + level[i][j]);
}
}
}
Now why isn't this working? It constantly says xmlDoc.getElementsByTagName("tiles")[0] is undefined and that xmlDoc.getElementsByTagName("tiles").length = 0. So what am I doing wrong?
I'd use XMLHttpRequest and its responseXML property instead, which will work in all major browsers. Example:
function readLevel(xmlDoc) {
alert(xmlDoc.documentElement.tagName);
// Your existing code goes here
};
var createXmlHttpRequest = (function() {
var factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
for (var i = 0, len = factories.length; i < len; ++i) {
try {
if ( factories[i]() ) return factories[i];
} catch (e) {}
}
})();
var xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
readLevel(xmlHttp.responseXML);
}
};
xmlHttp.open("GET", "levels/test.xml", true);
xmlHttp.send(null);
According to SitePoint, all the arguments are required in createDocument. Maybe the falsy values are tripping you up.

Categories