Plot data that retrieved from Firebase-Database (Realtime) - javascript
I've a problem with plotting an number array in Plotly. So, we can skip to subject without further ado.
Here is HTML code:
<script src="plotly.min.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.1/firebase-database.js"></script>
<div class="navbar"><span>Analog Plotter by remidosol</span></div>
<div class="wrapper">
<div id="chart"></div>
<script src="FireConfig.js"></script>
<script>
Plotly.plot('chart',[{
y:[analogval()],
type:'line'
}]);
var cnt = 0;
setInterval(function(){
Plotly.extendTraces('chart',{ y:[[analogval()]]}, [0]);
cnt++;
if(cnt > 300) {
Plotly.relayout('chart',{
xaxis: {
range: [cnt-300,cnt]
}
});
}
},15);
</script>
</div>
</body>
How can I plot number ARRAY that read from Firebase? I changed getData function's return code, once.(like I placed a num array parameter to getData, but it didn't make the plot.ly code work to plot data).
I could read data from Firebase but i couldn't plot it.
Here is view of my website and console:
It reads data but can't plot.
Would you help me please? What's wrong with this code? BTW, Firebase config block is okay, i changed it before create this subject.
I'm waiting for your help. Thank you from now.
Edit:
I can get data and convert it to number by replace and slice methods. It's correct now. But the plot.ly code still don't plot data line.
Following aforementioned function, here is the code below:
function analogval(){
databaseiot.orderByChild("analog").on('value', function(dataSnapshot) {
var arru = dataSnapshot.val().analog;
arru.toString();
arru = arru.replace(/\\r/g,'');
arru = arru.slice(1, 4);
arru = Number(arru);
console.log(arru);
return arru;
//arru = data.val().analog.split(",").map(Number);
})}
The issue is in your analogval() function. If I'm not mistaken, your current implementation of analogval () doesn't return anything. Your return statement is inside of the callback function that you passed to the .on() method. What you need is to have your analogval() function to return the value of the array.
One way to do this is to create a variable (e.g. array) visible to analogval() and set the value of array to be what you read from Firebase, then return array from analogval():
var array;
function analogval(){
databaseiot.orderByChild("analog").on('value', function(dataSnapshot) {
var arru = dataSnapshot.val().analog;
arru.toString();
arru = arru.replace(/\\r/g,'');
arru = arru.slice(1, 4);
arru = Number(arru);
console.log(arru);
array = arru;
});
return array;
}
Related
My object in javascript not returning the wanted value
I can't seem to figure out how to do the object part, I need to make it calculate the age dynamically. I've written most of the stuff here and it works fine the only down side is my dynamic age calculation, I don't know what I'm doing wrong and can't find my mistake. <html> <head> <title>WEB PROGRAMIRANJE</title> </head> <body> <script type="text/javascript"> var niza=new Array (9,8,7,6,5,4,3,2,1); var izbrisani=niza.shift(); var izbrisanip=niza.pop(); var sortirani=niza.sort(); // form an arrey delete first and last: // sort the arrey: document.write(sortirani); function babati(a,b,c) { var total; total=(a+b+c)/3; alert(total); } document.write("<br>"); </script> <input type="button" value="Call" onClick="babati(0,5,10)";> <script type="text/javascript"> document.write("<br>"); var ucenik=new Object(); // giving them value to object elements: ucenik.ime="Name"; ucenik.prezime="Surname"; ucenik.godina=2021; ucenik.roden=2003; // printing the object elements: document.write(ucenik.ime); document.write("<br>"); document.write(ucenik.prezime); document.write("<br>"); document.write(ucenik.roden); document.write("<br>"); // The function: // This will calculate the age dinamicly This year - Birth year: ucenik.vozrast=function() { this.godina - this.roden; } ucenik.vozrast(); document.write(ucenik.vozrast); //This line above prints the dynamic age: </script> </body> </html>
2 things. Firstly, the function isn't returning any value so running it won't result in any output. Secondly, in the document.write(ucenik.vozrast) it writes the function definition rather than running the function and writing the output. Below is the fixed code. ucenik.vozrast=function() { return this.godina - this.roden; } document.write(ucenik.vozrast());
first step you need to return your function expression. Something like this: ucenik.vozrast= function() { return this.godina - this.roden; } and when you want to paint that result in the DOM you can do something like this let actualYears = ucenik.vozrast() document.write(actualYears);
JSON from yahoo financial API SyntaxError when is given as parameter to google chart table [duplicate]
This question already has answers here: How do I return the response from an asynchronous call? (41 answers) Closed 5 years ago. I use yahoo financial API to get data from it and then I want to input the data in google chart, but it seems that I have a problem with the JSON object. So, I tried everything which I read , but unfortunately still unsuccessful. Error index.html:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at drawChart (main.js:18) at Object.google.a.c.Ac (loader.js:155) at Object.google.a.c.Pa (loader.js:155) at f (loader.js:152) at Object.google.l.m.kj (loader.js:229) at Object.google.l.m.ce (loader.js:229) at loader.js:228 JavaScript google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChart); var options = { 'title': 'Today is not my day', 'width': 400, 'height': 300 }; var input = getData(); function drawChart() { var chartData = google.visualization.arrayToDataTable(JSON.parse(input)); var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(chartData, options); }; function getData() { dataArray = [ ['Name', 'Volume'], ]; var BASE_URL = "https://query.yahooapis.com/v1/public/yql?q="; var yql_query = 'select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")'; var yql_query_str = encodeURI(BASE_URL + yql_query); var result = yql_query_str + "&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"; $.getJSON(result, function(data){ var object = data.query.results.quote; for (var i = 0; i < object.length; i++) { var currentObj = object[i]; var pushedArray = [currentObj.Name, parseFloat(currentObj.Volume)]; dataArray[i+1] = pushedArray; } return dataArray; }); }; HTML <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css"> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- <script type="text/javascript" src="js/request.js"></script> --> <script type="text/javascript" src="js/main.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12" id="chart_div"></div> </div> </div> <script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </body> </html>
As it is written above, getData() synchronously returns undefined, so inside of drawChart() you're essentially trying to JSON.parse(undefined), which leads to the SyntaxError you received (JSON.parse() casts undefined to the string "undefined", which is invalid JSON). dataArray is being returned from within the callback to $.getJSON() after the request returns; there is no way it could currently be accessible inside of the drawChart() function. You need to refactor the code so that drawChart() is called after the $getJSON() request has returned, and so it has access to dataArray either lexically or through a closure.
Get data from Materialize CSS chips
I need to get data from Materialize CSS chips, but I don't know, how. $('.chips-placeholder').material_chip({ placeholder: 'Stanici přidíte stisknutím klávesy enter', secondaryPlaceholder: '+Přidat', }); function Show(){ var data = $('.chips-placeholder').material_chip('data'); document.write(data); } <!-- Added external styles and scripts --> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css"> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- HTML body --> <div class="chips chips-placeholder"></div> <button onclick="Show()" type="button">Show</button>
So, to access to the data's chip you just have to do this: var data = $('#id of your chips div').material_chip('data'); alert(data[0].tag);` '0' is the index of your data (0, 1, 2 , 3, ...). 'tag' is the chip content. You can also get the id of your data with '.id'.
To get data from Materialize CSS chips, use the below code. $('#button').click(function(){ alert(JSON.stringify(M.Chips.getInstance($('.chips')).chipsData)); });
They appear to have changed the method available in the latest version. The documentation suggests that you should be able to access the values as properties of the object, but I’ve spent an hour looking, not getting anywhere. Until the following happened $('.chips-placeholder').chips({ placeholder: 'Enter a tag', secondaryPlaceholder: '+Tag', onChipAdd: (event, chip) => { console.log(event[0].M_Chips.chipsData); }, During the onChipAdd event I was able to access the event. Within this object was an array of tags. I know this isn't the documented way, however there is only so much time a client will accept when it comes billing and I must move on.
This worked great for me <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.chips'); var instances = M.Chips.init(elems, { placeholder: "Ajouter des Tags", secondaryPlaceholder: "+tag", onChipAdd: chips2Input, onChipDelete: chips2Input, Limit: 10, minLength: 1 }); function chips2Input(){ var instance = M.Chips.getInstance(document.getElementById('chip1')), inpt = document.getElementById('myInputField'); inpt.value = null; for(var i=0; i<instance.chipsData.length; i++){ if(inpt.value == null) inpt.value = instance.chipsData[i].tag; else{ inpt.value += ','+instance.chipsData[i].tag; //csv } } console.log('new value: ', inpt.value); } }); </script>
Automatic two way binding with Knockout
I'm just getting started with Knockout.js and i have a view(html) which is supposed to be populated by data from a rest api via jquery's $.getJSON method. When i run the app, nothing shows but using firebug i can see that the 'GET' query returns a status code of 200 and the right data. I'm at a fix as to why nothing shows in the view since the bindings in Knockout.js are supposed to be automatic. Below is my code. Thanks <div id ='main'> <!-- ko foreach: posts --> <p>Hello</p><span data-bind="text: title"></span></p><p data-bind="text: content"></p> <p data-bind="text: author"></p><p data-bind="text: date"></p> <!-- /ko --> </div> </body> <script type="text/javascript"> function Post(data){ this.title = ko.observable(data.title); this.content = ko.observable(data.content); this.author = ko.observable(data.author); this.date = ko.observable(data.date) } function PostListViewModel(){ var self = this; self.posts = ko.observableArray([]); $.getJSON("/posts", function(getPost){ var mappedPost = $.map(getPost, function(item){ return new Post(item) }); self.posts(mappedPost); }); } var postlistviewmodel = new PostListViewModel(); ko.applyBindings(postlistviewmodel); </script>
This should be: $.getJSON("/posts", function(getPost){ var mappedPosts = $.map(getPost, function(item){ return new Post(item) }); self.posts(mappedPosts); }); wouldn't do self.posts.push(mappedPosts[i]) at all. You should just pass mappedPosts through the ko binding in order to update the listeners. If your just getting the latest posts and want to update your current list simply do: var allPosts = self.posts().concat(mappedPosts); self.posts(allPosts); You don't need the model to have ko.observable if you're just displaying them. If you want to edit model as well, then leave as. Also, I tend to do this for single or multiple view models: ko.applyBindings({viewModel : new viewModel() }; This allows for having multiple named view models. Access scope using: $root.viewModel This is what I did earlier: http://jsfiddle.net/jFb3X/ Check your code against this fiddle then. Script tags also need to be above the closing body tags <html> <head> </head> <body> <!-- all your html content --> <script type="text/javascript"> var viewModel = function () { } ko.applyBindings({viewModel : new viewModel()}); </script> </body> </html>
Is it something as simple as waiting for the DOM to be ready? Are you able to try the following: $(function () { ko.applyBindings(postlistviewmodel); }); Source: I've done this a few times and been stumped for a bit trying to see what I did wrong. :-) (As a style thing, I'd also move the /body to after the /script - probably not related to your issue though).
I suspect you get multiple posts from /posts. You only push a single item (array). ... $.getJSON("/posts", function(getPost){ var mappedPosts = $.map(getPost, function(item){ return new Post(item) }); for(var i = 0; i < mappedPosts.length; i++) { self.posts.push(mappedPosts[i]); } }); ...
Extracting value from JSON generated source code on a page
I have the below JSON data that is present in the source of our product detail pages (this is an ecommerce site). I need to pull the "atrsell" value from each line using javascript/jquery. Can somebody give me the bext way to do this please? <script type="text/javascript"> $(document).ready(function(){ Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"6","att4":""},{"atronhand":24,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"6","atrsku":"505274940925","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"8","att4":""},{"atronhand":3430,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"8","atrsku":"505274940926","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"14","att4":""},{"atronhand":50,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"14","atrsku":"505274940922","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"12","att4":""},{"atronhand":3,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"12","atrsku":"505274940942","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"14","att4":""},{"atronhand":1,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"14","atrsku":"505274940943","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"16","att4":""},{"atronhand":322,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"16","atrsku":"505274940944","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"18","att4":""},{"atronhand":200,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"18","atrsku":"505274940945","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Navy","att3":"","att2":"10","att4":""},{"atronhand":431,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"10","atrsku":"505274940927","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"10.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Navy","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Phantom","att3":"","att2":"10","att4":""},{"atronhand":3443,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"10","atrsku":"505274940913","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"20.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Phantom","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Phantom","att3":"","att2":"12","att4":""},{"atronhand":99,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"12","atrsku":"505274940914","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"20.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Phantom","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Sweet Grape","att3":"","att2":"16","att4":""},{"atronhand":433,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"16","atrsku":"505274944584","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"68.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Sweet Grape","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); Attributes.StoreJSON({"att1":"Sweet Grape","att3":"","att2":"18","att4":""},{"atronhand":20,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"18","atrsku":"505274944585","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"68.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Sweet Grape","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null}); }); </script>
Try var arr = [], Attributes = { StoreJSON: function(obj1, obj2) { arr.push(obj2); } }; /* Your code here*/ var atrsells = arr.map(function(i){ return i.atrsell; });