Return arrays from meteor mongo - javascript

ajduke:bootstrap-tagsinput
I am using the above package to create a tags system. I have used <select multiple> from the True Input Value from the link above and have inserted each tags as Strings within the tag array.
This is what my db looks like.
Posts
tags //Array
[0] : sometag //String
[1] : sometag //String
[2] : sometag //String
//and so forth..
So my question is...
I want to return all the tags within a post to the following format, so that I can reuse it to show the tags when my users try to edit their posts.
Wanted Format
['sometag', 'sometag', 'sometag', and so forth]
Edit1
this is what I've done so far.
Post_Edit.js
Template.postEdit.rendered = function() {
myTags = Posts.findOne({_id: this._id}).tags.fetch(); //AAA
$('.tagsinput').tagsinput('add', myTags); //From above link API
}
I've tried other methods for //AAA line but I am having no luck.I've tried things such as Posts.findOne.map... Maybe my english comprehension is not up to par but the documentations in meteor did not help me understand any better.
Edit 2
Posts.findOne({_id: "ziZw3wLaxFyz3DYP4"}).tags
I've tried putting this in the browser console and got the array in the format that I wanted.
But the problem is, it won't work in my app when I use it.
When I use Posts.findOne({_id: this._id}).tags in my postEdit.rendered, I get this browser console error. Cannot read property 'tags' of undefined
Post_Edit.js
Template.postEdit.rendered = function() {
myTags = Posts.findOne({_id: this._id}).tags;
$('.tagsinput').tagsinput('add', myTags); //From above link API
}
What I don't understand is why is it working in browser console but not my Template.postEdit.rendered?

You are correct that your variable myTags is undefined when Template.postEdit.rendered is called because the Posts database has not finished loading when your function is called.
myTags = Posts.findOne({_id: this._id}).tags.fetch(); //AAA
Solution
There are multiple strategies including:
Updating DOM after subscription completes
http://docs.meteor.com/#/full/Blaze-TemplateInstance-subscribe
Re-run the function when Collection changes
http://docs.meteor.com/#/full/tracker_autorun
Template.postEdit.rendered = function() {
Tracker.autorun(function () { ** NEW LINE **
myTags = Posts.findOne({_id: this._id}).tags;
$('.tagsinput').tagsinput('add', myTags);
} ** NEW LINE **
}

I've approached a completely different way to figure this out.
But I'd still like to know why my method did not work...
post_edit.js
Template.postEdit.helpers({
tags: function(){
Posts.findOne({_id:this._id}).tags;
}
});
post_edit.html
<select class=tagsinput id="tagsinput" data-role="tagsinput">
{{#each}}
<option value="{{this}}">{{this}}</option>
{{/each}}

Related

JS Array not recognized as an array in Google Apps script

I am writing what should be a simple HTML form for users to make a reservation. However, having difficulty doing something I've done many times before - getting data from a GSheet and presenting it in an HTML form. Code snippets:
**Server side**
//Getting data from spreadsheet; expecting it to be an array of arrays.
function getMembers(){
const url = "https://my gsheet url"
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("Members");
const row = ws.getLastRow()
const memberData = ws.getRange(2,1,row-1,7).getValues();
const array = JSON.stringify(memberData); //EDIT...helps get data to client side
return //array; //this data to be passed to browser when called. Type Error?
//Log(memberData) = //Looks like an array to me...
//[1,"Simmie","Smith","Simmie Smith","2020-01-01T05:00:00.000Z","temp","53120-1"],
//[2,"Fred","Williams","Fred Williams","2020-01-01T05:00:00.000Z","temp","53120-2"],
//[3,"Carleton","Johnson","Carleton Johnson","2020-01-01T05:00:00.000Z","temp","53120-3"],
//[4,"Caroll","Williams","Caroll Williams","2020-01-01T05:00:00.000Z","temp","53120-4"],
//[5,"Gabby","Williams","Gabby Williams","2020-01-01T05:00:00.000Z","temp","53120-5"]
//EDIT HtmlService code
function doGet(e){
return HtmlService.createTemplateFromFile('Reservations HTML')
.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Calling the above server function when page loads so that member name can be presented in a select dropdown and other info from the array used elsewhere.
**Browser JS**
function getMemberData(){
google.script.run.withSuccessHandler(populateMembersDD).getMembers();
}
function populateMembersDD(data){
console.log(data) //undefined - same result FFox or Chrome..
memberInfo = data.filter(function(row){return true});
not getting any further than that because data is not passing to browser in a format with which I can apply necessary methods to get data into dropdown. Have tried various methods (slice, filter etc) to convert data into an array but none have worked. I suspect a type error, as though server function is not producing an object in array format. But I cannot figure out why. Have read many similar questions/answers on Stack but none have solved my problem. Help much appreciated as I am 24 hours in on solution experiments. Have many other apps where this basic code pattern works totally fine...

Turning API data into HTML

sorry for the newbie question.
I'm new to using API's and I want to take the data from here
https://api.guildwars2.com/v2/commerce/prices/24615 (specifically the unit price under sells:) and display this in HTML.
This project will be using the unit price data across roughly 100 id's and I'd like to organize these numbers and run some basic math with them.
How can I go about this?
fetch('https://api.guildwars2.com/v2/commerce/prices/24615')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
So far I can get the data into the console, but I'm not sure how to turn this into something I can work with.
There is function in jQuery to make API calls, the following code makes you access api data,
$(document).ready( function() {
var info;
var whitelisted;
var quantity;
$.get("https://api.guildwars2.com/v2/commerce/prices/24615",function(obj){
info = obj['id'];
whitelisted = obj["whitlelisted"]
quantity = obj.buys['quantity']
$("#id1").html("id :"+info);
$("#whitelist").html("whitelisted :"+whitelisted);
$("#quan").html("quantity :"+quantity);
});
});
for more info you could look into the following pen link to the code
ignore these jerk moderators.
In your callback function, where you log myJson, edit your previously created html file,
like if you have a div, <div id="myDiv"> </div>, in the response function do something like this
const myDiv = document.getElementById("myDiv")
myDiv.textContent = myJson.name
And your div will show the name from json, or whatever you need. Play around with these ideas and you'll get far

Django: populate the field based on previous field value - missing the last step to make it work

Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part.
Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form
merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(),
merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800,
initial='0.00',decimal_places = 2, max_digits=10)
Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request:
def check_item_price(request):
if request.method == "GET":
item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify
price = Merchandise.objects.get(id = item)
return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off?
and the url
url(r'^_item_price', views.check_item_price, name='_item_price' )
Calling the url manually works great, it returns the price in json format
And here is the javascript that is in the html form. The first part works, upon change it calls the url and a json object is returned, but the second part that should update the second field isn't working. I admit my lack of knowledge in javascript is probably at fault here. I tried many variations based on examples, none worked for me.
<script type="text/javascript">
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
$('#price').append("<option value=" + data.value + "></option>");
});
});
});
</script>
Any pointers on what to fix in the javascript?
Thanks!
After letting it marinate in my head for 2 months, I went back to it and finally made it work. Here is the right code
jQuery(document).ready(function() {
$('#merch').change(function() {
var item = $(this).find(':selected').val();
$.getJSON('/classes/_item_price/',{item:item},
function(data) {
document.getElementById('id_merch_price').value=data;
});
});
});
</script>
First, the ID wasn't precise enough, but also the way of updating it wasn't the right one it seems. I truly feel lost anytime I have to do research on javascript or jquery. So may ways to do the same thing, it's almost impossible to learn for a casual coder like me.

Breeze EntityManager.executeQuery with expand - httpResponse data does not match result data?

I'm working on a web app that uses Breeze and Knockout. I have the following function:
function getArticle(id, articleObservable) {
var query = EntityQuery.from('KbArticles')
.where("articleId", "==", id)
.expand("KbArticleType, KbSubject, KbArticleTags");
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (articleObservable) {
articleObservable(data.results[0]);
}
log('Retrieved [Article] from remote data source', data.results.length, true);
}
}
A 1 to many relationship exists between the KbArticles entity and the KbArticleTags entity. The goal of this function is to fetch a specific article and the list of tags associated with the article. The function executes successfully (and I DO get data for the other 2 expanded entities - they are 1 to 1), however, I get an empty array for the KbArticleTags in data.results. Interestingly, the tags are populated in data.httpResponse:
So, it appears that the data is coming over the wire, but it's not making it to the results in the querySucceeded function. I tried to step through the breeze code to determine how the httpResponse is mapped to the result, but got lost fairly quickly (I'm a javascript newb). Does anyone have any troubleshooting tips for figuring out why the expanded entity doesn't show in the results, but is returned in the httpResponse? Or am I trying to do something that isn't supported?
Ok, so for whatever reason (I probably deleted it one day while testing and didn't add it back), the navigation property (in my Entity Framework diagram) was missing on the KbArticleTag entity:
All I had to do was add that back and everything is working as expected.

Couchbase Java API and javascript view not returning value for a specific Key

I am using couchbase API in java
View view = client.getView("dev_1", "view1");
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(this.Key);
ViewResponse res=client.query(view, query);
for(ViewRow row: res)
{
// Print out some infos about the document
a=a+" "+row.getKey()+" : "+row.getValue()+"<br/>";
}
return a;
and the java script view in couchbase
function (doc,meta) {
emit(meta.id,doc);
}
So, when I remove the statement query.setkey(this.Key) it works returns me all the tables, what am I missing here .. How can I change the function to refect only the table name mentioned in the key
Change the map function like this:
function (doc,meta) {
emit(doc.table,null);
}
it is good practice not to emit the entire document like:
emit(doc.table, doc)
NB: This is surprisingly important:
i have tried using setKey("key") so many times from Java projects and setting the key using CouchBase Console 3.0.1's Filter Result dialog, but nothing get returned.
One day, i used setInclusiveEnd and it worked. i checked the setInclusiveEnd checkbox in CouchBase Console 3.0.1's Filter Result dialog and i got json output.
query.setKey("whatEverKey");
query.setInclusiveEnd(true);
i hope this will be helpful to others having the same issue. if anyone finds another way out, please feel free to add a comment about it.
i don't know why their documentation does not specify this.
EXTRA
If your json is derived from an entity class in a Java Project, make sure to include an if statement to test the json field for the entity class name to enclose you emit statement. This will avoid the key being emitted as null:
if(doc._class == "path.to.Entity") {
emit(doc.table, null);
}

Categories

Resources