Running a for loop on data from Facebook Graph Api - facebook

I am trying to dynamically show photos on my moms wedding website that she adds to her photos albums on Facebook but I am having trouble getting the images to render and loop. My get request is working and currently pulling in the image link and the id of each photo in the album. This is an example of the json that is returned.
{
"photos": {
"data": [
{
"picture": "https://scontent.xx.fbcdn.net/v/t1.0-0/s130x130/13879222_1235179076493734_1631898598554522774_n.jpg?oh=e6d74e7731f374be63a378e99ef3a88e&oe=58111449",
"id": "1235179076493734"
}
Here's my code so far
$.getJSON('https://graph.facebook.com/102060453138941?fields=photos{picture}&access_token=xxx',
function(fbResults) {
for(var i =0; i < fbResults; i++) {
$('.gallery').append(
'<img class="" src="https://graph.facebook.com/'+ this.id +'/picture" />'
);
}
});

Try this:
for(var i = 0; i < fbResults.photos.data.length; i++) {
$('.gallery').append(
'<img class="" src="https://graph.facebook.com/'+ fbResults.photos.data[i].id +'/picture" />'
);
}
Btw, you will only get 25 entries with the API. You can set a limit with the limit parameter or you can use paging: https://developers.facebook.com/docs/graph-api/using-graph-api/#paging
If you need to get all entries at once, i suggest using paging with a recursive function.
Btw, you would need to add the User Token to each line, which is a very bad idea. The whole code should better go to the server and you should actually download the photos and cache them. Just saying.

Related

How do I embed a Facebook Feed in the new Google Sites (using Apps Script)?

I've read that you can make a Google Apps Script that shows a Facebook Feed, and then embed this in a Google Site, but I can't find any more information on how to do it and I can't figure it out myself.
When I try to make an Apps Script web app with a Facebook feed I get errors like:
Uncaught DOMException: Failed to set the 'domain' property on 'Document': Assignment is forbidden for sandboxed iframes.
This is from copying the "Facebook Javascript SDK" and "Page Feed" from Facebook Developers into an HTML file and deploying it as a web app. I gather it has something to do with how Apps Script sandboxes your code but I don't know what I have to do here.
For that matter, even if I try to make a simpler Apps Script with some static HTML, when I try to embed it from Drive into the site I get an error "Some of the selected items could not be embedded".
The New Google Sites doesn't support Google Apps Script.
Related question: Google App Scripts For New Google Sites Release
The new Google Sites does now support embedding apps script (make sure to deploy the apps script as a web app, set the right permissions, and use the /exec url and not your /dev one to embed).
I found I couldn't use the facebook SDK for videos because of the sandboxing. I used an iframe solution instead for videos, but maybe you could try something like this for the feed (I'm assuming you've registered your app in fb so you can get generate tokens):
In apps script, create a .gs file and an html file, roughly along the lines below (I haven't actually worked with returning feeds, so check the returned data structure and adjust accordingly)
//**feed.gs**
function doGet(e) {
return HtmlService
.createTemplateFromFile('my-html-file')
.evaluate();
}
function getToken() { //use your fb app info here (and make sure this script is protected / runs as you
var url = 'https://graph.facebook.com'
+ '/oauth/access_token'
+ '?client_id=0000000000000000'
+ '&client_secret=0x0x0x0x0x0x0x0x0x0x0x0x'
+ '&grant_type=client_credentials';
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
return jsondata.access_token;
}
function getFeed() {
var url = 'https://graph.facebook.com'
+ '/your-page/feed'
+ '?access_token=' + encodeURIComponent(getToken());
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
//Logger.log(jsondata); //check this and adjust following for loop and html showFeed function accordingly
var posts = {};
for (var i in jsondata) {
posts[i] = {"post":jsondata[i].message};
}
return posts;
}
<!--**my-html-file.html**-->
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// The code in this function runs when the page is loaded (asynchronous).
$(function() {
google.script.run
.withSuccessHandler(showFeed)
.withFailureHandler(onFailure)
.getFeed(); //this function is back in .gs file and must return an array or object which gets auto-passed to the showFeed function below
});
function showFeed(posts) { //parameter name must match array or object returned by getFeed in gs file
var html = '';
for (var p in posts) {
html += '<p>' + posts[p].post + '</p>'; //instead of a string, you can build an array for speed
}
$('#feed').empty().append(html); //if you used an array for the html, you'd split it here
}
function onFailure(error) {
$('#feed').empty().append("Unable to retrieve feed: " + error.message); ;
}
</script>
</head>
<body>
<div id="feed">
Loading...
</div>
</body>
</html>

Not able to fetch Facebook friend photo

I not able to get user friends photos not profile picture. I can easily get profile picture
but not able to get user friend photos
I wrote this code but it is not working for me
FB.api('me/friends?fields=albums', function(response) {
for (var i=0; i<response.data.length; i++) {
var album = response.data[i];
FB.api('/'+album.id+'/photos', function(photos){
if (photos && photos.data && photos.data.length){
for (var j=0; j<photos.data.length; j++){
var photo = photos.data[j];
// photo.picture contain the link to picture
var image = document.createElement('img');
image.src = photo.picture;
document.body.appendChild(image);
}
}
});
}
});
Given all the required permission friends_photos,publish_stream
But still no luck .
Please help
Your graph url is off. To get a specific users photo album list you need:
{user_id}/albums?fields={list_of_album_fields}
In conjunction with
user_photos and/or friends_photos permissions
The Facebook graph explorer is an excellent tool for getting your graph url's right before coding. Try it out to verify this solution.
If you're looking to get all albums for all friends in a single pass you'll need to formulate this as either FQL or a batch request.

Soundcloud: How do I know the sound cloud track ID right away after uploading a track?

http://developers.soundcloud.com/docs/api
When I look at the API docs, I see
SC.stream("/tracks/293", function(sound){
sound.play();
});
When I look at the track I uploaded, it only provides me the permalink. How do I get the track ID from the website? Do I always have to do a /resolve to get the ID?
This is probably more manual steps than /resolve, but it is "from the website." The sound id also appears in the embed code when you go to the sound and click "Share".
For example, if you go to a sound page, e.g.:
https://soundcloud.com/lowcountrykingdom/another-ordinary-day
Then click "Share", which brings up a pop up. Click "Embed" to switch to the embed tab, and copy the Embed code, which will look something like:
<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/47580057&color=ff6600&auto_play=false&show_artwork=true"></iframe>
Note the ID in the value of the url query parameter:
url=https%3A//api.soundcloud.com/tracks/47580057
I'd use jquery ajax call to grab the data from Soundcloud. Say you save your variables permalink_url and client_id:
$.get('http://api.soundcloud.com/resolve.json?url='+
permalink_url+'/tracks&client_id='+client_id , function (result) {
console.log(result);
});
This should log an array of the songs. Check out this bin for reference http://jsbin.com/viviza/4/edit
Update: This answer is pretty old.
Soundclick docs https://developers.soundcloud.com/docs/api#uploading
The SC object now allows for getting the id's directly
SC.connect().then(function(){
return SC.get('/me/tracks');
}).then(function(tracks){
return tracks.map(function(track){
console.log("you can log the id here too: " + track.id")
return track.id
})
})
You could also get all the tracks from a given user id. Then use $.map() to place each of the tracks into an array. Call SC.stream() with song[i].id to play a random song from the array from the array of tracks.
SC.get('/users/123456/tracks/', function(tracks) {
// get an array of tracks
var song = $.map(tracks, function(i){
return i;
});
var i = Math.floor(Math.random() * song.length) // get a random value between 0 & the of songs in SC account -1
SC.stream(song[i].id, function(sound){
sound.play();
});
});
Using JavaScript to find the track data from a soundcloud song url:
let trackUrl = 'https://soundcloud.com/user-869590724/talk-to-animals-sentra-remix'
let client_id = '<your-client-id>'
let resolveUrl = `http://api.soundcloud.com/resolve.json?url=${trackUrl}/tracks&client_id=${client_id}`
fetch(resolveUrl, {
method: 'get'
}).then((response) => {
return response.json()
}).then((result) => {
/* now you have the track */
console.log(result)
})

Sharethis & Addthis

Has anyone figured out how to only increment share counts if the sharing action is completed?
They seem to count clicks.. not completed shares. That isn't a stat that is profoundly meaningful to me.
You can set it so the count displays the 'native' count:
<script type="text/javascript">stLight.options({
publisher:"Your publisher key", nativeCount:true
});</script>
However this only seems to work for Facebook, LinkedIn and a few others. For Twitter, I just replace the ShareThis count with the actual count obtained from the Twitter API, once ShareThis has loaded and the ShareThis markup exists on the page:
var pageUrl = 'http://www.google.com/';
updateTwitter();
function updateTwitter() {
if (jQuery('.st_twitter_vcount .stBubble_count').length > 0) {
jQuery.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + pageUrl + '&callback=?',
function(data) {
jQuery(".st_twitter_vcount .stBubble_count").html(data.count);
});
}
else {
setTimeout(function() {
updateTwitter();
}, 50);
}
}
Just change the pageURL variable to the URL you want to display statistics for.
Hope that helps,
Kamal.
Ended up rolling my own. Neither seems to support this.

Facebook Live feeds display inside my website

Facebook live Feeds display inside my website as FBML is deprecated instead of using that, is there any simplify method to do same task in java script, display feeds and comments to that feeds.
URL http://developers.facebook.com/docs/reference/javascript/
Fetching Current Logged in User's News Feed through JS:
FB.api('/me/home', function (response) {
console.log(response)
});
Corresponding HTTP GET
http://graph.facebook.com/me/home?access_token=UserAccessToken
EDIT (Simple Example)
Assuming you have extended permission read_stream
<input type="button" value="test" onclick="GetFeeds()" />
function GetFeeds() {
FB.api('/me/home', function (response) {
for (var i = 0, l = response.data.length; i < l; i++) {
var post = response.data[i];
var name = post.from.name;
var msg = post.message;
alert("Posted By: " + name + " Message: " + msg);
});
}