Access JSON kind of data from a div? - javascript

So I have a div which displays the results from Microsoft emotion API such as:
anger: 0.28446418
contempt: 0.00341128884
disgust: 0.000332433876
fear: 0.009447911
happiness: 0.02609423
neutral: 0.6288482
sadness: 0.00180563633
surprise: 0.04559612
Here is the code for displaying the data:
.done(function(data) {
// Get face rectangle dimensions
var faceRectangle = data[0].faceRectangle;
var faceRectangleList = $('#faceRectangle');
var data1="";
// Append to DOM
for (var prop in faceRectangle) {
data1 += "<li> " + prop + ": " + faceRectangle[prop] + "</li>";
}
faceRectangleList.html(data1);
// Get emotion confidence scores
var scores = data[0].scores;
var scoresList = $('#scores');
var data2="";
// Append to DOM
for(var prop in scores) {
data2 += "<li> " + prop + ": " + scores[prop] + "</li>";
}
scoresList.html(data2);
}).fail(function(err) {
alert("Error: " + JSON.stringify(err));
});
});
}
function make_graph(){
}
Now I need to plot a line from these scores.Can you tell me how to access each separate value of these scores in another function so that I can plot them as points in my graph?

Just call make_graph from inside the done callback, passing it the data, like this.
.done(function(data) {
// ... do what you already do
make_graph(data);
}).fail(function (err) {
alert("Error: " + JSON.stringify(err));
});
function make_graph(data) {
for (d in data) {
// do stuff with data
}
}

From the given information, you can make a function like this
function drawLine(dataScores) {
for (var d in dataScores) {
// dataScores[d] will give you the score
// rest of the relevent code
}
}
and call it like this
drawLine(scores);

I think it is not good practice to write data in HTML DOM, then read it back.
But if You need this, try something like this
plotData = []
var scoresList = $('#scores')
scoresList.children('li').each(function(i) {
data = i.thml()
plotData.push(i.split(':').map(i => [i[0].trim(), parseFloat(i[1])]))
});
// here You have all data in plotData
// [['anger', 0.28446418], ...]
// Draw Your plotData here

If you want to read it back from div li, here is a jquery function to covert html to jquery data object
$(document).ready(function(){
var dataArr={};
$("#scoresli" ).each(function( index ){
data=$( this ).text().split(":");
dataArr[data[0]]=data[1]
});
alert(JSON.stringify(dataArr));
});
//{"anger":" 0.28446418\n","contempt":" 0.00341128884"}

Related

Array gives errors after JSON function

I'm trying to check if the twitch stream is online or offline and if so change a background colour. If i check without the array and just put in the name it works, but with the array it doesn't (I don't have a lot of knowledge of JSON).
function test() {
var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"];
for (var i = 0; i < twitchChannels.length; i++) {
console.log(i + " " + twitchChannels[i]);
$.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannels[i] + '?client_id=XXXX', function(channel) {
console.log(i + " " + twitchChannels[i]);
if (channel["stream"] == null) {
console.log("Offline: " + twitchChannels[i])
document.getElementById(twitchChannels[i]).style.backgroundColor = "red";
} else {
console.log("Online: " + twitchChannels[i])
document.getElementById(twitchChannels[i]).style.backgroundColor = "green";
}
});
}
}
Error: http://prntscr.com/i6qj51 inside the red part is what happens inside of json fuction
Your code is quite weak since you didn't manage the callback of every get you make.
Also you didn't check if:
document.getElementById(twitchChannels[i])
is null, since the exception clearly stated that you can't get :
.style.backgroundColor
from nothing.
Basic check VanillaJS:
if(!document.getElementById("s"))
console.log('id ' + twitchChannels[i] + ' not found in dom')
else
console.log('id ' + twitchChannels[i] + ' found in dom')
Also consider mixing JQuery with VanillaJS extremely bad practice; use proper JQuery method to access dom element by ID .
You should pass twitchChannel to the function because the var i is changing, this is an issue like others already mentioned: Preserving variables inside async calls called in a loop.
The problem is that you made some ajax call in a cicle, but the ajax calls are async.
Whey you get the first response, the cicle is already completed, and i==4, that is outside the twitchChannels size: that's why you get "4 undefined" on your console.
You can change your code in such way:
function test() {
var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"];
for (var i = 0; i < twitchChannels.length; i++) {
executeAjaxCall(twitchChannels[i]);
}
}
function executeAjaxCall(twitchChannel){
$.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannel + '?client_id=XXXX', function(channel) {
console.log(twitchChannel);
if (channel["stream"] == null) {
console.log("Offline: " + twitchChannel)
$('#'+twitchChannel).css("background-color", "red");
} else {
console.log("Online: " + twitchChannel)
$('#'+twitchChannel).css("background-color", "green");
}
});
}
}
When console.log(i + " " + twitchChannels[i]); is called inside the callback function, the variable i has already been set to 4, and accessing the 4th element of array twitchChannels gives undefined since the array has only 4 elements.
This is because $.getJSON is a shorthand Ajax function which, as the name suggests, executes your requests asynchronously. So what actually happened is, based on the output you provided,
The loop is executed 4 times, and four Ajax requests have been sent.
The loop exits; i is already set to 4 now.
The ajax requests return; the callbacks are called, but the i value they see is now 4.
You can change the console.log inside your callback to something like console.log(i + " " + twitchChannels[i] + " (inside callback)"); to see this more clearly.
The correct result can be obtained by binding the current value of i to the closure.
function test() {
var twitchChannels = ["imaqtpie", "summit1g", "tyler1", "greekgodx"];
function make_callback(index) {
return function (channel) {
console.log(index + " " + twitchChannels[index]);
if (channel["stream"] == null) {
console.log("Offline: " + twitchChannels[index])
document.getElementById(twitchChannels[index]).style.backgroundColor = "red";
} else {
console.log("Online: " + twitchChannels[index])
document.getElementById(twitchChannels[index]).style.backgroundColor = "green";
}
}
}
for (var i = 0; i < twitchChannels.length; i++) {
console.log(i + " " + twitchChannels[i]);
$.getJSON('https://api.twitch.tv/kraken/streams/' + twitchChannels[i] + '?client_id=XXXX', make_callback(i));
}
}

Selecting item2 on page 1 returns item1 on page2

I am dynamically creating rows and tables from a database to display a list of read-only items. When one of these items is clicked, the page should reload to a different window and display the relevant results related to the clicked item.
I have 99% of this working, however when I click the first row (let's say "item1" the next window reflects undefined. When I click the second row ("item2") the window reflects the results of item1. When I click the third row ("item3") the window reflects the results of item2.
The most I understand is that I may not be storing the variables correctly.
My closest guess is this may be a solution for queryString, however I am not sure how or where to implement it.
I have provided all relevant code commented for the sake of anyone else who may have this problem.
var customApp = function(){
// Establish Variables
var salonName
var salonDomainLink
var salonAddress
var salonPhoneNumber
var salonSelection
// Queries Salons class
var query1 = new Parse.Query("Salons");
query1.find({
success: function(results) {
// Changes search results from JSON Object to ?something readable?
var searchResults = JSON.parse(JSON.stringify(results))
// Loops through every result and creates variables with each specific result
for ( var i in searchResults) {
salonName = searchResults[i].name;
salonDomainLink = searchResults[i].domainLink;
// Creates a new row for each item in table
var newrow = $('<tr>').text('').appendTo('#searchTable');
// Adds a cell for each salonName in row
var nameCell = $('<td>').text(salonName).appendTo(newrow);
// Adds an id of the salon name + 'Id' to each row
var cellId = nameCell.attr("id", salonName.replace(/\s+/g, '') + "Id")
// Changes class of each cell
nameCell.addClass("text-left font-w600 text-primary");
}
// Passes clicked salon name to a variable for use on another page
$('#searchTable tr td').click(function(){
// Acquires text value of the specific td of tr
salonSelection = $(this)[0].childNodes[0].nodeValue
// Saves the variable to local storage (can be retrieved with "localStorage.salonSelection")
delete localStorage.salonSelection;
window.localStorage.salonSelection = salonSelection;
window.location = 'base_pages_schedule_1.html';
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message + ". Please contact Support.");
}
});
query1.equalTo("name", localStorage.salonSelection);
query1.find({
success: function(results) {
var searchResults = JSON.parse(JSON.stringify(results))
// Loops through every result and creates variables with each specific result
for ( var i in searchResults) {
window.localStorage.salonName = searchResults[i].name;
window.localStorage.salonDomainLink = searchResults[i].domainLink;
window.localStorage.salonAddress = searchResults[i].address;
window.localStorage.salonPhoneNumber = searchResults[i].phoneNumber;
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message + ". Please contact Support.");
}
});
$('#salon-name').text(localStorage.salonName);
$('#salon-address').text(localStorage.salonAddress);
$('#salon-phone-number').text(localStorage.salonPhoneNumber):};
query.find() is asynchronous so it won't set new values until after you set the text() in the dom
Move the dom updates into your find() success callback
query1.find({
success: function(results) {
var searchResults = JSON.parse(JSON.stringify(results))
// process results
// then update dom
$('#salon-name').text(localStorage.salonName);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message + ". Please contact Support.");
}
});
Also note that your for loop is rewriting a new value to the storage keys on each iteration of the loop so only the last one gets stored. Not sure what your storage objectives are here

I am trying to write a trigger in parse.com but some error

Parse.Cloud.afterSave("StatusTable", function(request) {
var deviceName = request.object.get("deviceName");
var lastSeen = request.object.get("entryTime");
var sectionName = request.object.get("sectionName");
var LastSeen = Parse.Object.extend("LastSeen");
var query = new Parse.Query(LastSeen);
query.equalTo("deviceName", deviceName);
query.first().then(function(result) {
result.put("lastSeen", lastSeen);
result.put("sectionName", sectionName);
result.save();
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
);
I have two tables in parse. StatusTable and LastSeen table.I need to write a trigger which updates lastSeen and sectionName columns of LastSeen table when a successful insert has occurred in StatusTable corresponding to the deviceName.This code is not working.
StatusTable
LastSeenTable
From the Object documentation: https://parse.com/docs/js/api/classes/Parse.Object.html
There is no put() method. Try using set() instead:
query.first().then(function(result) {
result.set("lastSeen", lastSeen);
result.set("sectionName", sectionName);
result.save();
});
Also, are you sure you want your query to use first instead of find? Just to ensure that you are always updating the object that you want.

Query with javascript in LightSwitch HTML client

LightSwitch tables in play:
ProductVariant
ProductVariantDetail (many to one ProductVariant)
Code:
myapp.AddEditProduct.Id_render = function (element, contentItem) {
var detailArray = new Array();
//contentItem.screen.getProductVariantDetails().then( function(result) {
// for (var i in result.data) {
// if (result.data[i].ProductVariant.Id == contentItem.value) {
// detailArray.push(result.data[i].InventoryDetail.Title);
// }
// }
// $("<div>" + detailArray.join(" / ") + "</div>").appendTo($(element));
//});
var filter = "ProductVariant eq " + contentItem.value;
myapp.activeDataWorkspace.ApplicationData.ProductVariantDetails.filter(filter).
execute().then(function (result) {
for (var i in result.results) {
detailArray.push(result.results[i].InventoryDetail.Title);
}
}).then(function() {
$("<div>" + detailArray.join(" / ") + "</div>").appendTo($(element));
});
};
The commented out code goes through EVERY ProductVariantDetail and checks if the corresponding ProductVariant matches the custom control. I discovered you can retrieve a query client-side (to save server bandwidth, see uncommented code) but my version never makes it inside filter(filter).execute. I tried "ProductVariant.Id eq" for the filter as well. Does anyone know what I might be doing wrong?
Try using this
var filter = "(ProductVariant.Id eq " + msls._toODataString(contentItem.value,":Int32")+")";

Using D3 to read data into associative arrays

I'm trying to loop through a set of values and read in separate files (using d3.js) into javascript associate arrays , but the argument is not being passed properly into the internal function. For example:
var reg_list = [];
var all_region_data = [];
reg_list[0]="region1";
reg_list[1]="region2";
// Function to read in data from all regions in reg_list.
function read_regional_data(region_list) {
for (i=0;i<reg_list.length;i++) {
region = region_list[i];
console.log("Read data for " + region) // THIS RETURNS REGION1, THEN
// REGION2
all_region_data[region]=new Array()
d3.csv('filepath' + region + '.csv', function(csv){
console.log('reading for ' + region) // THIS RETURNS REGION2 TWICE
csv.map(function(x) {
all_region_data[region].push(x.cause);
})
console.log("Finished Reading Data for " + region)
})
}
}
When I execute this, I iterate through both regions in the loop, but region1 is never passed into the d3.csv function. This may have something to do with the d3.csv being run asynchronously? Any thoughts on how to avoid or improve this are appreciated.
Use recursion instead of the loop to iterate over the regions --
var reg_list = [],
all_region_data = [];
reg_list[0]="region1";
reg_list[1]="region2";
function read_regional_data(i) {
var region = reg_list[i];
console.log("Read data for " + region);
all_region_data[region]=new Array();
d3.csv('filepath' + region + '.csv', function(csv){
console.log('reading for ' + region);
csv.map(function(x) {
all_region_data[region].push(x.cause);
});
console.log("Finished Reading Data for " + region);
if(i < reg_list.length) {
read_regional_data(i+1);
}
});
}
read_regional_data(0);

Categories

Resources