How to get values data from child - javascript

How to get last 20 records from firebase? I got:
dataset: undefined undefined
My firebase looks like this:
my code
var rootRefData = db.ref().child("users_db/user1/dataset");
rootRefData.once("value", snap => {
var key = snap.key;
var timestamp = snap.val().timestamp;
var log = snap.val().log;
var custom = "";
// create line chart
custom += key + ": " + timestamp + " " + log + "<br />";
console.log(custom);
counter++;
$("#chartsl-container-all").append(custom);
});

Try this:
var rootRefData = db.ref().child("users_db/user1/dataset");
rootRefData.once("value", snap => {
snap.forEach(function (snapshot) {
var key = snapshot.key;
var timestamp = snapshot.val().timestamp;
var log = snapshot.val().log;
var custom = "";
rootRefData is at node dataset, since you want to get timestamp and log, then you need to iterate inside the randomid using forEach to be able to get those values and the random id.

Related

Show parsed JSON data in a list

I have a JSON file with data that is downloaded from my SQL server. I parse the data with the following code:
var dataParsed = JSON.parse(data);
var dataString = JSON.stringify(data)
var interestsVar = document.getElementById("interests").innerHTML
var result = dataParsed.filter(x => x.interests === interestsVar);
var resultString = JSON.stringify(result)
var matchesID = document.getElementById("matches")
var tagLi = matchesID.getElementsByTagName("li")
var li = "<li>" + resultString + "</li>";
if (document.getElementById("matches").innerHTML.includes(li)) {
} else {
document.getElementById("matches").innerHTML = document.getElementById("matches").innerHTML + li;
document.getElementById("matchesCount").innerHTML = "You have " + tagLi.length + " matches."
count()
}
That all works, I am able to get the data in the list that matches the search/interests box. I currently have it so it displays them in a list. I am wondering if there is a way to make them show up in a box and when they click a button they can either mark them as "ok" or "no", and basically shuffle through the options.

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

JS: OpenWeatherMap API returns "undefinded" for parameter "rain.3h"

I'd like to have some parameters from this API in my "home.php".
I already got values for parameters cloud, min & max temp, wind etc. ...
But in case of rain.3h my console shows an error, because of the number "3" behind the point. So i put it into brackets and it returns now "undefinded". Do you have any suggestions to solve this problem? (Parameter rain is set for this JSON response because i see the value in the browser-console.
Here´s my code:
function getWeatherData(weatherlat, weatherlong) {
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" + weatherlat + "&lon=" + weatherlong + "&units=metric&APPID=88e60f2ce52794ed240874b235f21794";
$.ajax({
url: url
}).done(data => {
let nextForecast = data.list[0].main;
let cloudy = data.list[0].clouds;
let weatherCond = data.list[0].weather[0];
let windy = data.list[0].wind;
let rainy = data.list[0].rain;
console.log(data);
$('#progressbar2').addClass('hidden');
//"<img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png' alt='Icon depicting current weather.'>"
document.getElementById("weathercond").innerHTML = `${weatherCond.description}`;
document.getElementById("weathericon").innerHTML = "<img src='http://openweathermap.org/img/w/" + weatherCond.icon + ".png' alt='Icon depicting current weather.'>";
document.getElementById("cloud").innerHTML = `${cloudy.all}%`;
document.getElementById("mintemp").innerHTML = `${nextForecast.temp_min}°C`;
document.getElementById("maxtemp").innerHTML = `${nextForecast.temp_max}°C`;
document.getElementById("luftftgk").innerHTML = `${nextForecast.humidity}%`;
document.getElementById("windrtg").innerHTML = `${windy.deg}°`;
document.getElementById("windspeed").innerHTML = `${windy.speed}m/s`;
document.getElementById("rainfall").innerHTML = `${['rainy']['3h']}mm`;
});

Text not appearing when using Twitter intent to create custom tweet

Problem
I'm trying to using twitter intent to tweet out a pre-written, custom tweet. But when I click fa-twitter the box appears blank. I think the problem may be how I'm encoding the URL?
scripts.js
function shareTeam(){
$(".fa-twitter").click(function(){
// Create an empty array
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
// console.log(lastNames);
// var regularNames = lastNames.slice(0, 3); // Same as below, but no shuffling
var regularNames = lastNames;
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
regularName4 = regularNames[3]; // Defenseman
regularName5 = regularNames[4]; // Defenseman
regularName6 = regularNames[5]; // Goalie
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
// This is zero-indexed? So the numbers will be one lower than the actual teaser #
var teaser = "teaser";
var rand = Math.floor(Math.random() * 6);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?";
var twitterUsername = "#stltoday";
var interactiveURL = "http://staging.stltoday.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your own all-team #STLBlues team: ";
var teaser2 = "My #STLBlues dream team has " + regularName3 + " and " + regularName4 + ". Build your own: ";
var teaser3 = "My #STLBlues dream team has " + regularName4 + " and " + regularName5 + ". Build your own: ";
var teaser4 = "My #STLBlues team will skate circles around yours! Pick your team: ";
var teaser5 = regularName6 + " with the glove save! ";
var teaser6 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice: ";
// Push teasers into array
teasers.push(teaser1);
teasers.push(teaser2);
teasers.push(teaser3);
teasers.push(teaser4);
teasers.push(teaser5);
teasers.push(teaser6);
// This is the full url that will be switched in and out
var fullURL = "text="+teasers[rand]+"&url="+interactiveURL+"&via=("+twitterUsername+")";
// var fullURL = interactiveURL+"&via="+twitterUsername+"&text="+teasers[rand];
console.log(fullURL);
// It needs to be encoded properly as well
var encodedURL = baseURI+encodeURIComponent(fullURL);
// Change the href to the link every time the Twitter button is clicked
$(".link--twitter").attr("href", encodedURL);
console.log(encodedURL);
// if (lastNames.length === 6) {
// } else {
// var encodedURLGeneric = baseURI+encodeURIComponent(fullURL);
// $(".link--twitter").attr("href", encodedURLGeneric);
// }
});
}
The solution was to encode each part individually
function shareTeam(){
$(".fa-twitter").click(function(){
// Create an empty array
var teasers = [];
// Grabs the names of all the players in the span
// Sets a variable marking the indexOf each of the names
// If the index doesn't find a space, it returns -1, which returns the full name
// Otherwise it will return only what follows the space
var lastNames = $("li span").map(function() {
var name = $(this).text();
var index = name.indexOf(" ");
return index == -1 ? name : name.substring(index + 1);
}).get();
var regularNames = lastNames.slice(0, 4); // Same as below, but no shuffling
regularName1 = regularNames[0]; // Forward
regularName2 = regularNames[1]; // Forward
regularName3 = regularNames[2]; // Defenseman
regularName4 = regularNames[3]; // Defenseman
// Find me a random number between 1 and 3
// Where 1 is the start number and 3 is the number of possible results
// This is zero-indexed? So the numbers will be one lower than the actual teaser #
var teaser = "teaser";
var rand = Math.floor(Math.random() * 3);
console.log(rand);
// Concatenate the two strings together
teaseRand = teaser.concat(rand);
// These are the components that make up that fullURL
var baseURI = "https://twitter.com/intent/tweet?text=";
var twitterUsername = "stltoday";
var interactiveURL = "http://staging.stltoday.com/STLblues";
// Randomly generate one of three teasers
var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your #STLBlues team:";
var teaser2 = "My #STLBlues dream team has " + regularName3 + " and " + regularName4 + ". Build your own:";
var teaser3 = regularName4 + " to " + regularName3 + " back to " + regularName2 + " — GOAL! Create your #STLBlues team:";
var teaser4 = "Pick your #STLBlues dream team from 50 of the best #StLouisBlues to hit the ice:";
// Push teasers into array
teasers.push(teaser1);
teasers.push(teaser2);
teasers.push(teaser3);
teasers.push(teaser4);
// This is the full url that will be switched in and out
// It needs to be encoded properly as well
var fullURL = baseURI+encodeURIComponent(teasers[rand])+"&url="+encodeURIComponent(interactiveURL)+"&via="+encodeURIComponent(twitterUsername);
var genericURL = baseURI+encodeURIComponent(teasers[3])+"&url="+encodeURIComponent(interactiveURL)+"&via="+encodeURIComponent(twitterUsername);
console.log(fullURL);
console.log(genericURL);
// Change the href to the link every time the Twitter button is clicked
$(".link--twitter").attr("href", fullURL);
console.log(fullURL);
if (lastNames.length === 6) {
console.log("Yeah, yeah, yeah");
} else {
$(".link--twitter").attr("href", genericURL);
}
});
}

min & max of values in looped-thru JSON data (no jQuery)

In the following:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
} // processResponse
if (weighInData[obj].user === selUser) { ... returns the following (using example Ron):
Object { user="Ron", date="2014-08-01", weight="192"}
Object { user="Ron", date="2014-08-02", weight="195"}
Object { user="Ron", date="2014-08-03", weight="198"} ... etc.
... so my problem presently is where this belongs:
var peakWeight = Math.max.apply(Math, weights);
console.log("peakWeight: " + peakWeight);
Since I'm only after the weight values for the matching user, I assumed it would have to run within the 'if (weighInData[obj].user === selUser) { ... ', but this (and numerous other attempts in and out of the loop, including a for loop within the selUser) fail to achieve the desired results. In fact, even when the math function wasn't running on each value in 'weights', (i.e., outside the loop) and only ran outside the loop, the result was an incorrect value.
Any insight is greatly appreciated,
svs
Here's a very simple example you can probably adjust to fit your purpose:
// create this array outside of for loop so it already exists
var arr = [];
// test data
var a = { user:"Ron", date:"2014-08-01", weight:"192"};
var b = { user:"Ron", date:"2014-08-02", weight:"195"};
var c = { user:"Ron", date:"2014-08-03", weight:"198"};
// within for loop, you should only need to push once (per loop)
arr.push( a.weight );
arr.push( b.weight );
arr.push( c.weight );
// after the loop ends, display loop, get max and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
http://jsfiddle.net/biz79/sb7zayze/
If i were to edit your code, something like this might work:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
// ADDED: create array
var arr = [];
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
// ADDED: add to array
arr.push(weights);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
// ADDED: after the loop ends, display loop, get max/min and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
} // processResponse

Categories