Get data from database and append data to aframe - html

I want to get data from database and append that data to aframe. I did and data is getting from the database but not appending to the aframe scene. Here is my working flow.
This index file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<a-scene id="scene">
<a-camera id="camera" position="0 0 2" >
</a-camera>
<a-sky color="#000"></a-sky>
</a-scene>
<script>
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "data.php";
var asychronous = true;
ajax.open(method,url,asychronous);
ajax.send();
ajax.onreadystatechange = function(){
if(this.readyState==4 && this.status==200){
var data = JSON.parse(this.responseText);
console.log(data);
var html = "";
var username = "";
for(var i=0;i<data.length;i++){
username = data[i].username;
html += "<a-scene>";
html += +username;
html += "</a-scene>";
}
var totalText1 = document.createElement('a-text');
totalText1.setAttribute('position',{x:0, y:0, z:0});
totalText1.setAttribute('color',"#fff");
totalText1.setAttribute('value',username);
totalText1.setAttribute('scale',{x:1.6, y:1.6, z:1.6});
document.getElementById("scene").appendChild(totalText1);
}
}
</script>
</body>
</html>
Here is data.php file
<?php
$conn = mysqli_connect("localhost","root","","test");
$query = "SELECT * FROM usertest WHERE language='english'";
$result = mysqli_query($conn,$query);
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data = $row;
}
echo json_encode($data);
?>
Data retrieving is okay.But is there any way to append those data to aframe scene?

Double check the entity is actually getting appended to the scene. It looks right. Check the Inspector (ctrl/alt/i) or DOM Inspector or query selector from console. The 0/0/0 position might just make it hard to see.

Related

How to add latest TimesStamp to Google Gauge

I need help adding latest TimesStamp to page that displays Google gauge. I have made gauge work and auto refresh without the need to refresh the page, but now I need to display on it, or next to it when the latest entry in database was made (displaying TimesStamp of value that is currently displayed in gauge). Here's my code so far:
Chart.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 800, height: 240,
greenFrom: 98, greenTo: 100,
yellowFrom:90, yellowTo: 98,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 240px;"></div>
</body>
</html>
And here's getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
we need to include the timestamp in the data we return from php.
first, add the field to the select statement, here...
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
next, we use a variable to save the timestamp...
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
then, in the while loop, we save the value of the timestamp...
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
finally, we combine both the chart data and timestamp in an object to send to the page.
$data = array('rows' => $data, 'timestamp' => $stamp);
following is the updated php snippet...
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
mysqli_close($conn);
// write data array to page
$data = array('rows' => $data, 'timestamp' => $stamp);
echo json_encode($data);
?>
then on the html page, we need to adjust how we receive the data...
to receive the chart data, we need to use the 'rows' property from the data.
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows); // <-- add .rows
and we can receive the timestamp as follows...
jsonData.timestamp
not sure how you want to display the timestamp, here a <div> is used.
so to update the new <div> element...
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
following the updated html snippet...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows);
chart.draw(data, options);
// update timestamp
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="timestamp"></div>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>

createElement Unique Identifier

I am building a little gallery in Html and I am having some trouble with it. I have a for loop that creates an img every time it iterates. The problem is that once I have all the images produced and I try to pass a unique variable to my other function which displays the clicked image, there are no unique values I can pass.
I'm probably not explaining it well, but if you run it you'll see what I mean. Any help figuring out how I can obtain a unique identifier for each of the thumbnails would be greatly appreciated.
Below is the code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function loadPictures(){
var a = new Array();
a[0] = '1-m';
a[1] = '2-m';
a[2] = '3-m';
document.getElementById('inWin').innerHTML='<img src="images/1-m.png" width="620px" height="auto" />';
var ci = document.getElementById('pics');
var newImg, divIdName;
for(x=0; x<a.length; x++)
{
newImg = document.createElement('img');
divIdName = 'portrait'+x;
newImg.setAttribute('id',divIdName);
newImg.setAttribute('src', 'images/' + a[x] + 'thumb.png');
newImg.setAttribute('onclick','changeContent(x);'); // for FF
newImg.onclick = function() {changeContent(x);}; // for IE
ci.appendChild(newImg);
}
}
</script>
<script>
function changeContent(num){
alert(num);
var a = new Array();
x=num;
a[0] = '1-m';
a[1] = '2-m';
a[2] = '3-m';
document.getElementById('inWin').innerHTML='<img src="images/'+ a[x] +'thumb.png" width="620px" height="auto" />';
}
</script>
</head>
<body onload="loadPictures()">
<div id="inWin">
</div>
<div id="pics">
</div>
</body>
</html>
Since I am a newer member I can't upload the image, sorry.
Each of the images already has a unique identifier, the ID attribute. You can work with this in different ways to get what you want. here's an idea of what it would look like:
<script>
var a = [ '1-m',
'2-m',
'3m'
];
function loadPictures(){
document.getElementById('inWin').innerHTML='<img src="images/1-m.png" width="620px" height="auto" />';
var ci = document.getElementById('pics');
var newImg, divIdName;
for(x=0; x<a.length; x++)
{
newImg = document.createElement('img');
divIdName = 'portrait'+x;
newImg.setAttribute('id',divIdName);
newImg.setAttribute('src', 'images/' + a[x] + 'thumb.png');
if(document.addEventListener)
newImg.addEventListener('click', changeContent, false);
else if(document.attachEvent)
newImg.attachEvent('onclick', changeContent);
ci.appendChild(newImg);
}
}
function changeContent(){
x = this.id.split('portrait')[1];
document.getElementById('inWin').innerHTML='<img src="images/'+ a[x] +'.png" width="620px" height="auto" />';
}
</script>

How to put the data taken from google custom search API to checkbox list

I have a code which takes data from google custom search API, There is no wrong with the custom search API part, it retrieves data without any error
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>
Required data are saved in the pageName, pageLink and pageDetails arrays.
Now I want display them with chechboxes and allow user to select them.
I need to take the links of the selected sites(pageLink variable) and pass it to anothe file using POST method
I tried using bellow code just before end of the body tag()
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
But in the other file, it says variables are undefined. seems like variables doesn't pass to the 'b.php' file
Can anyone please tell me how to do this?
Your current code for adding checkboxes would likely be executed before the search result arrives (i.e.: before hndlr is executed), so all arrays are still empty. The solution would be to move the checkbox creation code into the hndlr function.
Here's the fixed page.
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<form id="bform" action="b.php" method="post">
<input type="submit" name="formSubmit" value="Submit" />
</form>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
var f=document.getElementById('bform'), prev=f.children[0];
for (var i = 0; i < response.items.length; i++) {
var ele, item = response.items[i];
pageName[i] = item.title;
pageLink[i] = item.link;
pageDetails[i] = item.htmlSnippet;
ele = document.createElement('BR');
f.insertBefore(ele, prev);
prev = ele;
ele = document.createTextNode(pageName[i]);
f.insertBefore(ele, prev);
prev = ele;
ele = document.createElement('INPUT');
ele.type = 'checkbox';
ele.name = 'formDoor[]';
ele.id = i;
ele.value = encodeURI(pageLink[i]);
f.insertBefore(ele, prev);
prev = ele;
}
}
// Some codes
var search_query = 'https://www.googleapis.com/customsearch/v1?key=MY_KEY&cx=XXXXXXXXX&q='+query+'&start=1&callback=hndlr';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);
</script>
</body>
</html>

Google MAPs api v2 AJAX not working

My code is not working what is going wrong I can't understand...my code is:
/* =================Call.php========================*/
<?php
/* Include settings My mysql database */
include ("config.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>GG-Tracker (GSM and GPS location combined)</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=myAPIKey&sensor=true" type="text/javascript"></script>
<?php
echo "
<script type=\"text/javascript\">
var map;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(\"map\"));
downloadUrl(\"phpsqlajax_genxml.php\", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName(\"marker
\");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute(\"lat\"));
var lon = parseFloat(markers[i].getAttribute(\"lon\"));
var html = \"<b>\" + \"</b> <br/>\" ;
var marker = new GMarker(new GLatLng(lat, lon));
map.addOverlay(marker);
}
}
}
}
function downloadUrl(url, callback) {
if (window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else
{
request=new ActiveXObject(\"Microsoft.XMLHTTP\");
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing();
callback(request, request.status);
}
};
request.open(\"GET\", url, true);
request.send();
}
function doNothing() {}
</script>
";
?>
</head>
<body onload="load()" onunload="GUnload()">
<center>
<div id="map" style="width: 800px; height: 600px"></div>
</body>
</html>
/* End of =============Call.php===============*/
My phpsqlajax_genxml.php for genrating XML is:
/* Start of ===========phpsqlajax_genxml.php=============== */
<?php
require("phpsqlajax_dbinfo.php");
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
$connection=mysql_connect ($dbhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("tid",$row['TID']);
$newnode->setAttribute("devid",$row['DevID']);
$newnode->setAttribute("ldate",$row['LDate']);
$newnode->setAttribute("ltime",$row['LTime']);
$newnode->setAttribute("lat", $row['Lat']);
$newnode->setAttribute("lon", $row['Lon']);
$newnode->setAttribute("speed", $row['Speed']);
}
echo $dom->saveXML();
?>
/*=========End of=============phpsqlajax_genxml.php*/
My Database information file is: phpsqlajax_dbinfo.php
/*=========Start of=== phpsqlajax_dbinfo.php============*/
<?php
$dbhost = "localhost";
$username="root";
$password="";
$database="mygps";
$gmaps = "AIzaSyCRf9drwSYjBSeKpvSkEHFKqX_yBpq-Tkk";
?>
/*===========End of phpsqlajax_dbinfo.php==============*/
the above three files cant work.
If I run only phpsqlajax_genxml.php file to generate XML it is working
I can generate XML but it cannot downloaded through JAVA - I think AJAX call is not
working....
What to do auto reload marker from MySQL on some time interval without
reloading whole page like Live Tracking.....
Please Help Me My above code is not working
Thanks for Reading
Pradip
The V2 API is deprecated and you should migrate to V3 of the API.
https://developers.google.com/maps/documentation/javascript/
Is there any reason for using php-echo to output HTML-source?
However, if the code above is really what you actually use, you have a problem here:
var markers = xml.documentElement.getElementsByTagName(\"marker
\");
the line-break will break your script, remove it.

How to get info from background_page to popup?

I'm following the official Chrome Extension tutorial called Chritter where they fetch tweets from Twitter and place them into the extension. I'm trying to do similar except im trying to fetch items from an xml file.
My XML
<xml>
<item>
<title>Title 1</title>
<description>Description 1</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
<item>
<title>Title 2</title>
<description>Description 2</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
</xml>
background.html
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new items (30s)
var req; // request object
var unreadCount = 0; // how many unread items we have
var items; // all currently fetched items
getItems();
//setInterval(getItems, fetchFreq);
function getItems(){
req = new XMLHttpRequest();
req.open("GET", "http://urltoxml.com/xmlfile.xml", false);
req.onload = processItems;
req.send();
}
function processItems(){
xmlDoc = req.responseXML;
items = xmlDoc.getElementsByTagName("item");
unreadCount += items.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
items = xmlDoc.concat(items);
}
</script>
</head>
</html>
I don't know how to get the fetched items from the background.html and displayed onto the popup.html ?
popup.html
<html>
<head>
<link rel="stylesheet" href="popup.css" />
<script src="util.js"></script>
<script>
var bg; // background page
// timeline attributes
var timeline;
var template;
var title;
var link;
var description;
onload = setTimeout(init, 0); // workaround for http://crbug.com/24467
// initialize timeline template
function init() {
chrome.browserAction.setBadgeText({text: ''});
bg = chrome.extension.getBackgroundPage();
bg.unreadCount = 0;
timeline = document.getElementById('timeline');
template = xpath('//ol[#id="template"]/li', document);
title = xpath('//div[#class="text"]/span', title);
content = xpath('//div[#class="text"]/span', template);
update();
}
function update(){
// how to do this ?
// See Chritter example below with JSON,
// except i want to it with xml ?
}
</script>
</head>
<body>
<div id="body">
<ol id="timeline" />
</div>
<ol id="template">
<li>
<div class="text">
<a></a>
<span></span>
</div>
<div class="clear"></div>
</li>
</ol>
</body>
</html>
The way the Chritter extension does it only seems to work with JSON. Here is how they do it:
// update display
function update() {
var user;
var url;
var item;
for (var i in bg.tweets) {
user = bg.tweets[i].user;
url = 'http://twitter.com/' + user.screen_name;
// thumbnail
link.title = user.name;
link.href = openInNewTab(url);
image.src = user.profile_image_url;
image.alt = user.name;
// text
author.href = openInNewTab(url);
author.innerHTML = user.name;
content.innerHTML = linkify(bg.tweets[i].text);
// copy node and update
item = template.cloneNode(true);
timeline.appendChild(item);
}
}
Chritter background.html
<html>
<head>
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new tweets (30s)
var req; // request object
var unreadCount = 0; // how many unread tweets we have
var tweets; // all currently fetched tweets
getTweets();
setInterval(getTweets, fetchFreq);
// fetch timeline from server
function getTweets() {
req = new XMLHttpRequest();
req.open('GET', 'http://twitter.com/statuses/public_timeline.json');
req.onload = processTweets;
req.send();
}
// process new batch of tweets
function processTweets() {
var res = JSON.parse(req.responseText);
unreadCount += res.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
tweets = res.concat(tweets);
}
</script>
</head>
</html>
Any help much appreciated! Thanks!
If you want to access items var from a background page then:
var items = chrome.extension.getBackgroundPage().items;
I am not sure what the exact question is, but the general practice is to store the data from background page into localstorage and then access this data from the popup page.
http://www.rajdeepd.com/articles/chrome/localstrg/LocalStorageSample.htm