One JSON file with multiple getJSON requests - javascript

I currently have the following javascript file:
$(function () {
'use strict';
getAlbums();
});
function getAlbums() {
'use strict';
var name = '',
photos = '',
id = '',
displayAlbum = '',
albumThumb = '',
albumImage = '',
albumCaption = '';
$.getJSON('/assets/js/images.json', function (data) {
var album = data.albums;
$.each(album, function (i, item) {
name = item.name;
id = item.id;
photos = item.photos;
displayAlbums(name, id, photos);
});
});
}
function displayAlbums(name, id, photos) {
var displayAlbum = $('.templates .albums .thumb').clone(true),
thumbnail = displayAlbum.find('.thumbnail'),
image = displayAlbum.find('.thumbnail .image'),
caption = displayAlbum.find('.thumbnail .caption h4');
caption.html(name);
thumbnail.attr('id', id);
image.attr('src', photos[0].href);
image.attr('alt', photos[0].href);
$('.img-container .row').append(displayAlbum);
}
function displayGallery(request) {
'use strict';
var test = $(request).attr('id'),
gallery = '',
displayImages = '';
$('.img-container').hide();
}
The JSON files has a list of albums, each with a name, ID, and an array of image links to my assets folder. What I currently am doing is I'm loading the first image on each album as a thumbnail that will link to the gallery of remaining images. So if I click on one album thumbnail, that specific gallery will load.
What I'm having trouble with is the album thumbnails load with the page. What I need to do next is make it so that when I click on one of the albums, it will make a call to load that specific gallery.
So my question is, do I need to make a separate 'getJSON' function to load the gallery? Or can I use the same 'getAlbums' function I've already defined?
Here is a sample of my json file as well:
{
"albums": [
{
"name": "Ancillary & Specialty Rooms",
"id": 1,
"photos": [
{
"href": "/assets/images/specialty rooms/1.jpg",
"title": "image 1"
},
{
"href": "/assets/images/specialty rooms/2.jpg",
"title": "image 2"
},
{
"href": "/assets/images/specialty rooms/3.jpg",
"title": "image 3"
},
{
"href": "/assets/images/specialty rooms/4.jpg",
"title": "image 4"
},
{
"href": "/assets/images/specialty rooms/5.jpg",
"title": "image 5"
},
{
"href": "/assets/images/specialty rooms/6.jpg",
"title": "image 6"
}
]
},
{
"name": "Bathrooms",
"id": 2,
"photos": [
{
"href": "/assets/images/bathrooms/1.jpg",
"title": "image 1"
},
{
"href": "/assets/images/bathrooms/2.jpg",
"title": "image 2"
},
{
"href": "/assets/images/bathrooms/3.jpg",
"title": "image 3"
},
{
"href": "/assets/images/bathrooms/4.jpg",
"title": "image 4"
},
{
"href": "/assets/images/bathrooms/5.jpg",
"title": "image 5"
}
]
}
]
}
I appreciate any help I can get,
Thanks
UPDATE:
To specify more about what I want it to do. When a user clicks on the album for the gallery they want to view, the current div containing the album links will be hidden (or cleared, no sure yet) and the gallery will load on the same page.

$(displayAlbum).click(function() {displayGallery(this)})
What I'm thinking is that in your displayAlbums function just after you create displayAlbum by cloning from an existing element you can attach an onClick handler. When this is called - by the user clicking in the thumbnail it will call displayGallery. 'this' passed to displayGallery will be the clicked thumbnail - so you can examine this to get which thumbnail was clicked maybe off the id attribute you have.
I don't know what you want to do in displayGallery? Open in a new div?
This should work - or something like it.
Update:
I tried to figure out how you could do
$(displayAlbum).click(function() {displayGallery(this, photos)})
where photos is the JSON you have from your getJSON request which you've passed to displayAlbums()
Basically you should be able to pass the gallery part of the JSON to the click handler. So that when the thumbnail is clicked you can access that JSON. I ran into a problem with scope and eventually got a proof of concert to work on: JSFiddle: https://jsfiddle.net/justinwyllie/cj3h17hd/
Of course since you are not using a loop; you may not have this problem. You may be able to pass photos directly to your click handler without a problem.
Also - I'd add I'm not sure why you are creating a new element (the thumbnail) by cloning from something already on the page. As I'm sure you know you can just create new elements on the fly with jQuery e.g. $('#el').append('<span />'). I don't know the pros and cons of your cloning approach.

Related

Wix Velo — How to work with Array of Object

I'm currently building a website on Wix, and have come across a problem I can't think myself out of. Neither Wix support or the Wix Velo Forum have been able to help me out.
I have a repeater that is connected to the Stores/Products collection, and in the Stores/Products collection there's a collection field that contains additional info sections on the product. I have three info section; Tempo, Genre and Tags. Each contains a description.
It looks like this:
[
{
"title": "Tempo",
"description": "<p>142 BPM</p>\n"
},
{
"title": "Genre",
"description": "<p>Jazz</p>\n"
},
{
"title": "Tags",
"description": "<p>Frank Ocean, Travis Scott</p>\n"
}
]
I have figured out how to pull the individual objects with this code:
export function audioRepeater_itemReady($item, itemData, index) {
let product = $item('#dataset3').getCurrentItem(itemData._id)
let ArrayAdditionalInfo = []
ArrayAdditionalInfo = product.additionalInfoSections
ArrayAdditionalInfo.forEach((element) => {
console.log(element.title)
console.log(element.description)
})
But I want it to be able to figure out if eg. the Title === "Genre", then it will show the description from that array, like this:
{
// if equal to this:
"title": "Genre",
// show me this
"description": "<p>Jazz</p>\n"
},
The whole plan with this is to show the description output in a text element that I can implement in the repeater.
I have tried with if statements, but I just can't put it together myself. If this is confusing I'll gladly elaborate.
Thank you in advance.
I'm not a 100% sure if I understood the question correctly, but if you want to show all titles, and, conditionally the description if the title is Genre, you could just use a Ternary:
let data = [{
"title": "Tempo",
"description": "142 BPM\n"
},{
"title": "Genre",
"description": "Jazz\n"
},{
"title": "Tags",
"description": "Frank Ocean, Travis Scott\n"
}];
data.forEach(e => $("#products").append(
`<p>Title: ${e.title}${
e.title === "Genre"
? "<br>description: " + e.description
: ""
}</p>`
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="products">
</div>
I think your issue related to handler. You use repeaters onItemReady handler, which is not the best option for your case. It calls for each row in repeater. Instead of this I recommend to use dataset's onReady
$w("#dataset3").onReady( () => {
console.log("The dataset is ready");
$w("#audioRepeater").getItems(0, 20).then( (result) => {
let items = result.items;
items.forEach((element) => {
if (element.title === 'Genre') {
doWhatDoYouWant(element)
}
})
} ).catch( (err) => {
let errMsg = err.message;
let errCode = err.code;
} );
} );
Please take into consideration that this block should be inserted into $w.onReady

Adaptive card(user input form) in BotFramework V4 nodejs gets reprompted after user submit

async feed_first(stepContext)
{
let company_card = MessageFactory.attachment(
CardFactory.adaptiveCard(testfeedback)
);
return await stepContext.prompt("textPrompt", {
prompt: company_card
});
}
async feed_second(stepContext) {
console.log("enter feedback second");
console.log(stepContext.context.activity.value);
}
{
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "Container",
"items": [
{
"type": "Input.ChoiceSet",
"placeholder": "Placeholder text",
"choices": [
{
"title": " 1",
"value": " 1"
},
{
"title": " 2",
"value": " 2"
}
],
"style": "expanded",
"id": "cho"
},
{
"type": "ActionSet",
"actions": [
{
"type": "Action.Submit",
"title": "Submit"
}
]
}
]
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
}
so for this code what happens is, the card gets displayed, but on the bot emulator when the submit button is clicked, nothing happens. the console displays " Running dialog with message activity" and the same card is prompted again. the bot doesn't flow to the second step(feed_second) of waterfall dialog. what i would like for the code to do is to display "enter feedback second" on the console and then show the selected choice with the id "cho" for stepContext.context.activity.value agiain on the console. side note- i have added "feed_first" and "feed_second" while declaring the WaterfallDialog, so that's not the the issue
If you want to use an Adaptive Card's inputs with a text prompt, you will need to access the activity's value and serialize it into the activity's text somehow, as seen in this example. This information is in the dialogs section of my Adaptive Cards blog post, which you should read.
In JavaScript you can serialize the value into text like this:
/**
*
* #param {TurnContext} turnContext
*/
async sendValueToDialogAsync(turnContext)
{
// Serialize value
var json = JSON.stringify(turnContext.activity.value);
// Assign the serialized value to the turn context's activity
turnContext.activity.text = json;
// Create a dialog context
var dc = await this.dialogs.createContext(turnContext);
// Continue the dialog with the modified activity
await dc.continueDialog();
}
In your case, if you only need the result of one input then you can just use that property instead of serializing anything:
turnContext.activity.text = turnContext.activity.value.cho;

JavaScript google gapi spreadsheets.create not setting title, using 'Untitled speadsheet'

When I use the following, the sheet is created, but the title isn't being set.
When I use the api explorer, it creates with the right title. Using this documentation:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/create?apix_params=%7B%22resource%22%3A%7B%22properties%22%3A%7B%22title%22%3A%22x%22%7D%7D%7D
var request = gapi.client.sheets.spreadsheets.create({ "properties": { "title": "x" } }, {});
in the response:
...
title: "Untitled spreadsheet"
...
var request = gapi.client.sheets.spreadsheets.create({ "properties": { "title": "x" } });
Removing the second object was all I needed.

Get Chrome pageAction icon to appear for an URL list in JSON

I am currently developing a Chrome Extension and I want that the pageAction icon appears for an amount of URL's (around 500).
In my background.js file (among other code), I have this:
// Called when the url of a tab changes
function checkForValidUrl(tabId, changeInfo, tab) {
// If the tabs url starts with "http://specific_domain"
if (tab.url.indexOf('http://specific_domain') == 0) {
// Shows the page action
chrome.pageAction.show(tabId);
}
};
// Listen for any changes to the URL of any tab
chrome.tabs.onUpdated.addListener(checkForValidUrl);
I can get it to work on a specific site already, but I want to change the 'http://specific_domain' to a list of permitted sites, like a white list. I have access to a JSON file that is online.
Here's a snippet of it:
{
"antelife.com": {
"fbid": "AntElifecom",
"type": "store",
"name": "AntElife"
},
"amazon.com": {
"fbid": "Amazon",
"type": "store",
"name": "Amazon"
},
"ebay.com": {
"fbid": "eBay",
"type": "store",
"name": "eBay"
},
"mobilegeeks.com": {
"fbid": "mobilegeekscom",
"type": "publisher",
"name": "Mobile Geeks"
}
}
I want to extract the domains, and somehow iterate for all of them and if they are on the list, the pageAction icon should appear. Something like this:
function checkForValidUrl(tabId, changeInfo, tab) {
for (var i = 0, iLength = whiteListUrl.length; i < iLength; i++) {
if (tab.url.indexOf('http://www.'+whiteListUrl[i]) > -1) {
chrome.pageAction.show(tabId);
notification.show();
break;
}
}
};
chrome.tabs.onUpdated.addListener(checkForValidUrl);
Any kind of help should be useful. Many thanks.
If you have a json string you can get url's list in this way;
var urlObj = JSON.parse(jsonString);
var whiteListUrl = Object.keys(urlObj);

Getting Open Graph object ID from page URL

how can I get the Facebook Object ID paired to a page from the page itself?
For example, I asked directly for the Object ID 325186347604922 and i got:
<pre>
{
"url": ".../ricetta-bigne_salati.htm",
"type": "ricettepercucinare:recipe",
"title": "Bignè salati",
"image": [
{
"url": ".../magazine/wp-content/uploads/2013/03/101-150x150.jpg",
"width": 150,
"height": 150
}
],
"description": "Gli ingredienti e la procedura per preparare la ricetta Bignè salati.",
"data": {
"course": "Antipasto",
"foreign_id": 130400
},
"updated_time": "2013-03-28T10:12:17+0000",
"id": "325186347604922",
"application": {
"id": "118665634826424",
"name": "Ricettepercucinare.com",
"url": "https://www.facebook.com/apps/application.php?id=118665634826424"
}
}</pre>
But how, for example, this page http://www.ricettepercucinare.com/ricetta-bigne_salati.htm could know its own ID?
Thank you.
Its not currently possible to look up an object ID from the URL - although it should be.
It should be possible using:
http://graph.facebook.com/?id=http://www.ricettepercucinare.com/ricetta-bigne_salati.htm
but this isn't working.
Please raise a bug at developers.facebook.com/bugs
What about this guy's solution: http://blog.odbol.com/?p=9
function facebookGetIdForUrl(url, callback) {
//see http://developers.facebook.com/docs/reference/fql/object_url/
FB.api({
method: 'fql.query',
query: "SELECT id FROM object_url WHERE url = '" + url + "'"
}, function(response) {
callback(response[0].id);
});
}
facebookGetIdForUrl("http://facebook.com", function (id) {
alert("Facebook ID = " + id);
});
It's possible with FQL:
select id, url from object_url where url in ('http://www.watchth.is/movies/9166-baraka')
See it in the Graph API Explorer, or simply use this ajax call: https://graph.facebook.com/fql?q=select%20id%2C%20url%20from%20object_url%20where%20url%20in%20('http%3A%2F%2Fwww.watchth.is%2Fmovies%2F9166-baraka')&format=json&suppress_http_code=1
Thanks to Rees' response to a similar question

Categories