how to use jade/pug conditionals inside a script block? - javascript

i'm struggling to get this working. im actually using Chart.js and trying to populate my graphs with arrays of data.
so my code looks like
block lower-scripts
script.
var data = {
labels : [
each visit in visitstats
#{visit.date},
],
the output i get looks like
<script>var data = {
labels : [
each visit in visitstats
04/17/2016,
],
and i dont think that is right. should it print the each statement out into the html output?
I've tried following a few questions but cant get this working.
It doesn't look like the each statement runs. tried using the - to make it run. tried the pipe in front of the js to make it the exception. nothing.
can anyone show me where i'm going wrong?

Put a hidden input tag in your body in jade e.g.
body
input(type="hidden", id="visit-stats-json", value= JSON.stringify(visitstats) )
script.
var visitStatsValue = document.getElementById("visit-stats-json");
var visitStatsJSON = JSON.parse( visitStatsValue );
var labelsArray = [];
for( var i = 0; i < visitStatsJSON.length; i++ )
{
var visit = visitStatsJSON[i];
labelsArray.push( visit.date );
}//for
var data = { labels: labelsArray };
Now your data variable should have the value you want.
Edit:
I use exactly the same syntax and it works. Please note that there is a space after value=. If it still doesn't work, you can also try following way to achieve the same result:
-var visitStatsString = JSON.stringify(visitstats);
input(type="hidden", id="visit-stats-json", value= visitStatsString )

Can use inline interpolation:
script.
var visitstats = #[JSON.stringify(visitstats)];
...

Related

Printing JSON Data into innerHTML getting undefined - [object]

Hi guys Im trying to print a list of scores saved within a database, ive got the data as JSON data (see below)
I am trying to print all each object within the "Scores" array using the following code
function showScores() {
var ourRequest = new XMLHttpRequest();
var x, i = "";
ourRequest.open('GET', '/allScores');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
for (i in ourData.scores) {
x += ourData.scores[i] + "<br>";
}
document.getElementById("scoresList").innerHTML = x;
};
ourRequest.send();
}
However it is printing out the following
Any help with this is greatly appreciated, thanks guys
This line tries to append a raw object to your HTML string:
x += ourData.scores[i]
Javascript can’t magically parse this into HTML for you, so it just outputs [object Object].
You need to build a string from the individual parts of this object and print that instead. For example:
Note that you should not use for ... in with an array
ourData.scores.forEach(function (score) {
x += `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
});
Which would output something like this for each score:
[H] Arsenal 2 - 2 Newcastle [A]
Be sure to set x = "" before the loop otherwise the string will still start with undefined.
In case you’re interested: there are more succinct ways of writing this loop. Using Array.map() for instance:
let x = ourData.scores.map(score => {
return `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
}).join();
This expression does not require initialization of x beforehand.
you can create the elements as string and you can join the entire array and assign it to the innerHTML, as shown below.
You can change the structure, here for example i had made to ul , li you can create table or whatever format.
Note if you want to just append it, since the object you can't directly append it using JSON.stringify which will convert your object into string.
I hope this will solve your issue. Please let me know if any other issue you are facing.
var jsonObj = {scores: [{"Away_Score": 2, "Away_Team": "Newcastle", "Home_Score": 2, "Home_Team": "Arsenal"}, {"Away_Score": 2, "Away_Team": "Napoli", "Home_Score": 4, "Home_Team": "Liverpool"}]}
var html = jsonObj.scores.map(o => {
return `<ul><li>${o.Away_Team}</li><li>${o.Away_Score}</li><li>${o.Home_Team}</li><li>${o.Home_Score}</li></ul>`
})
document.getElementById("todaysData").innerHTML = html.join("")
<div id="todaysData">
</div>

Adding 3 drop down text values in jscalc.io

I created a simple calc with jscalc.io and I'm having trouble parsing values so I can add them.
I have played with a few variations of the following code but no luck. My javascript knowledge is really limited, like this is the first time writing something in JS. :)
jscalc.io returned the following error for this code:TypeError: null is not an object (evaluating 'inputs.Age.value')
"'use strict';
var varAge = parseFloat(inputs.Age.value);
var varWeight = parseFloat(inputs.Weight.value);
var varGender = parseFloat(inputs.Gender.value);
return {
total: varAge + varWeight + varGender
};
Any help would be much appreciated, thanks!
Just going to preface this by saying that I've never used jscalc.io, but I looked at the example and it looks like you're supposed to use inputs.Age instead of inputs.Age.value. Also, if you make your inputs as Numbers, you don't need to use parseFloat. So your fixed code would look like this:
'use strict';
var varAge = inputs.Age;
var varWeight = inputs.Weight;
var varGender = inputs.Gender;
return {
total: varAge + varWeight + varGender
};

Parse.com issues while querying array of pointers, .include not getting nested pointer data in cloud code

I am having trouble getting data from the nested pointers in my array of pointers from a query. I have an array of pointers like so: [{"__type":"Pointer","className":"QuizData","objectId":"rmwJrV55c7"},{"__type":"Pointer","className":"QuizData","objectId":"2132q8i9np”}, etc…]
That QuizData class also has a column named “ad” which is a Pointer to the “Ads” class. I can get the QuizData in a query using the following include statements on my query like so:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include("quizAdArr”);
__quizAdQueueQuery.include(["quizAdArr.QuizData"]);
BUT Neither of these or both combined don’t work as when I try to get column data from the ad it’s always undefined:
__quizAdQueueQuery.include(["quizAdArr.QuizData.ad"]);
__quizAdQueueQuery.include(["quizAdArr.QuizData.Ads"]);
This is my return from that query, where the column data "mediaType" that I am trying to access is always undefined:
return __quizAdQueueQuery.first().then(function(__resultsObj)
{
__quizQueueObj = __resultsObj;
__userQuizQueueArr = __quizQueueObj.get("quizAdArr");
var __quiz;
var __ad;
var __seenAd;
var __lengthInt = __userQuizQueueArr.length;
var __mediaTypeStr = __request.params.mediaType;
var __matchedQuizzesArr = [];
for (var __i = 1; __i < __lengthInt; __i++)
{
__quiz = __userQuizQueueArr[__i];
// console.log('__quiz.get("name") = '+__quiz.get("name"));
__ad = __quiz.get("ad");
// console.log("__ad.id = "+__ad.id);
//THE MEDIA TYPE IS ALWAYS RETURNING UNDEFINED HERE!!!
console.log('__ad.get("mediaType") = '+__ad.get("mediaType")+', __mediaTypeStr = '+__mediaTypeStr);
if (__ad.get("mediaType") == __mediaTypeStr)
{
//put all matches in array to be sorted
__matchedQuizzesArr.push(__userQuizQueueArr[__i]);
console.log("__matchedQuizzesArr.length = "+__matchedQuizzesArr.length);
}
}
return __matchedQuizzesArr;
});
Thanks for any help you can give! I also posted this as a bug in the Parse/Facebook issue reporter but was redirected here, so if this is a bug I can reopen it: https://developers.facebook.com/bugs/923988310993165/
EDIT Here is the updated, working query with nested includes for clarity:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include('quizAdArr');
__quizAdQueueQuery.include('quizAdArr.ad');
This should work (you only need to list the column names):
query.include('quizAdArr.ad');
Here's why:
You're querying QuizAdQueue so you don't need to list that
The QuizAdQueue class has an array in quizAdArr so you include it: query.include('quizAdArr');
Each quizAdArr element is a QuizData with an ad so you include it: query.include('quizAdArr.ad');
The issue was that you were including QuizData which is the name of a class and not a column name

Parse xml with Jquery and Javascript

I would like to parse the following xml flow :
<telhdl:leg>
<tel:deviceId>82085625</tel:deviceId>
<tel:media>AUDIO</tel:media>
<tel:state>ACTIVE</tel:state>
<tel:capabilities>
<tel:drop>true</tel:drop>
<tel:hold>true</tel:hold>
<tel:mute>true</tel:mute>
<tel:sendDtmf>true</tel:sendDtmf>
</tel:capabilities>
</telhdl:leg>
<telhdl:leg>
<tel:deviceId>82085625</tel:deviceId>
<tel:media>VIDEO</tel:media>
<tel:state>ACTIVE</tel:state>
<tel:muted>true</tel:muted>-
<tel:capabilities>
<tel:drop>true</tel:drop>
<tel:unMute>true</tel:unMute>
</tel:capabilities>
</telhdl:leg>
As you can see, there is 2 groups of leg, but in one of them there is an attributes which is not present in the other (muted) for example.
I have tried to parse it using this code :
$(xmlDoc).find('telhdl\\\\:deviceId,deviceId'); with $(xmlDoc) is the document node.
It works fine, but i don't know how to parse correctly this file to have as result an array which contain information of the 2 legs block.
The question is more : How to have clerary a result of the parsing ?
This should do the trick:
$(xmlDoc).find("telhdl").each(function() {
var deviceId = $(this).find("deviceId").text();
var media = $(this).find("media").text();
....etc....
var array = new Array(deviceId,media,...etc...);
});

question regarding serializeArray and passing into url

I am not totally familiar with javascript, jquery.
I am trying to do the following. Note a-f are names for the dropdown menus. Can someone help clarify? thanks
var a_params = $("#a").serializeArray();
var b_params = $("#b").serializeArray();
var c_params = $("#c").serializeArray();
var d_params = $("#d").serializeArray();
var e_params = $("#e").serializeArray();
var f_params = $("#f").serializeArray();
params.push({ name: 'menu_mode', value: '2-1' });
$.get("./scripts/model.cgi", a_params,b_params,c_params,d_params,e_params,f_params, function(data){
$("#grapharea").html(data);
$("#prog").html(" ");
});
More Comments: in the cgi script i am dumping the inputs to see if i am receiving the values from the a-f_params but this isn't the case. Any ideas why?
You have to create 1 array(or jquery-object in this case) from all object's, and serialize this array.
$('#a,#b,#c,#d,#e,#f').serializeArray();
But this is only needed, if you dont want to serialize e.g. all input-fields.
Otherwise you can use simply
$('#form').serializeArray();

Categories