I'm trying to list all blog posts with the Blogger API v3:
<script type="text/javascript">
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
$('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
$('.post p').html(Object.keys(response.items[i].title));
}
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>
This does append 3 divs (because of 3 posts) to my content div. But the content of each of this divs is:
<p>
"1"
"2"
"3"
"4"
"5"
</p>
I have no clue why, though I assume that title is an attribute of items[].
Any solutions or clues?
Thanks for answers!
You should removed Object.keys() and try this:
<script type="text/javascript">
function handleResponse(response) {
var post_number = Object.keys(response.items).length; //number of posts
for (i=0; i<post_number; i++) {
$('#content').append('<div id="post' + (i+1) + '" class="post"><p></p></div>');
$('.post p').html(response.items[i].title);
}
}
</script>
<script src="https://www.googleapis.com/blogger/v3/blogs/1961645108677548855/posts?callback=handleResponse&key=AIzaSyAJESQB3ddltUcDbZif3LUnX-Gzr18tBRg"></script>
In you case you shouldn't use Object.keys()
You request doesn't use the maxResults parameter and limited number of posts is retrieved so I recommend to use Google JavaScript Client Library - Blogger API and recursively retrieve all posts of a blog.
See the following example:
<script>
function renderResults(response) {
if (response.items) {
for (var i = 0; i < response.items.length; i++) {
//do whatever you want with the posts of your blog
}
}
if(response.nextPageToken) {
var blogId = 'XXX Your blogId XXX';
var request = gapi.client.blogger.posts.list({
'blogId': blogId,
'pageToken': response.nextPageToken,
'maxResults': 100,
});
request.execute(renderResults);
}
}
function init() {
gapi.client.setApiKey('XXX Get your API Key from https://code.google.com/apis/console XXX');
gapi.client.load('blogger', 'v3', function() {
var blogId = 'XXX Your blogId XXX';
var request = gapi.client.blogger.posts.list({
'blogId': blogId,
'maxResults': 100,
});
request.execute(renderResults);
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
Related
Below is my JavaScript code for calling the server API:
<script type='text/javascript'>
call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) {
document.getElementById('show').innerHTML=response;
});
</script>
When I print the response in an HTML tag:
<h1 id='show'></h1>
I'm getting results in this format:
{"code":"200","status":"Success:Mail Credit Details","Mail Credits":"46"}
But what I want is a result like this:
<h1>code:200</h1>
<h1>status:Success:Mail Credit Details</h1>
<h1>Mail Credits:46</h1>
I tried the following, but nothing was displayed:
var obj=['show']
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["code"]+"</td>";
var td2="<td>"+obj[i]["status"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
First of all you'll need 3 h1 elements, so change the 'show' element to a div like this;
<div id='show'></div>
Then in your javascript code, access response elements by their name like this;
<script type='text/javascript'>
call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) {
var obj = JSON.parse(response);
for(var prop in obj) {
document.getElementById('show').innerHTML += '<h1>' + prop + ":" + obj[prop] + '</h1>';
}
});
I want to return a datatable I created in google apps script with data from a Spreadsheet to the client. I use a succesHandler to get the data and use this to create a chart. The only problem i have is that my data is null. It seems i can't return a datatable object to the client page.
I need to send it to the client, because Google Apps script is deprecating the UIApp functions so i need the google.visualization functions in the Client.
Code.gs
function doGet() { return HtmlService.createHtmlOutputFromFile('Index.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);}
function getDataTable()
{
var bestanden = DriveApp.searchFiles('title contains "' + "kwalrap" + '"');
while (bestanden.hasNext())
{
var bestand = bestanden.next();
var docid = ( bestand.getId() );
Logger.log(docid);
};
var sheets= SpreadsheetApp.openById(docid).getSheets();
//vanaf sheet 0. tot hij bij de laatset sheet is. dan steeds 2 sheets verder.
for(var j = 0; j < 2; j = j+1)
{
var sheet = sheets[j];
//Logger.log(sheet.getSheetName());
var range = sheet.getRange(2,1,sheet.getLastRow(),8);
var inforange = sheet.getRange(2,1,1,8);
var values = range.getValues();
var infovalues = inforange.getValues();
var data = Charts.newDataTable()
.addColumn(Charts.ColumnType.STRING, "Tijd")
.addColumn(Charts.ColumnType.NUMBER, "dco")
.addColumn(Charts.ColumnType.NUMBER, "dcp")
.addColumn(Charts.ColumnType.NUMBER, "dct")
.addColumn(Charts.ColumnType.NUMBER, "dcz")
.addColumn(Charts.ColumnType.NUMBER, "ldc")
.addColumn(Charts.ColumnType.NUMBER, "lv")
for(var i = 0; i < sheet.getLastRow()-1; i++)
{
data.addRow([values[i][0],values[i][1],values[i][2],values[i][3],values[i][4],values[i][5],values[i][6]]);
Logger.log(values[i]);
}
var dataTable = data.build();
return dataTable;
// return JSON.stringify(values);
}
}
Index.html
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function onSuccess(data) {
var options = {
title: 'Why doesn't this work'
};
new google.visualization.LineChart(
document.getElementById('visualization_div')).draw(data, options);
}
google.script.run.withSuccessHandler(onSuccess)
.getDataTable();
</script>
</head>
<body>
<div id="visualization_div" style="width: 600px; height: 380px;';"></div>
</body>
</html>
why is my data variable null in the onSuccesHandler and how do i get the datatable in the client
Thanks for your help
Its because you need to return a plain javascript array, not a data table which is purely a server-side object.
I am trying to get the URL for all the photos of a facebook page.
How do I get the 'source' URL for this query and JSON structure:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=19292868552%3Ffields%3Dalbums.fields(photos.fields(source))&version=v2.1
I am using this success callback from a JSONP request:
function(response) {
for (i = 0; i < **???response.albums.data.length???**; i++) {
alert(**???response.albums.data[i].photos.data[i].source???**)
}
}
Can you help me find the right structure for the parts with the astericks? Because it has two [i]'s i think i'm getting confused..
You need to make sure that you have this in your head:
<script type='text/javascript' src='//connect.facebook.net/en_US/sdk.js'></script>
<script type='text/javascript' src='workFromPage.js'></script>
Now on workFromPage.js
var pre = onload;
onload = function(){
if(pre)pre();
if(!FB)reload();
var photoURLs = [];
// change userId
// make sure you test for login and wrap around code below, if needed
FB.api('/userId/albums', function(resp){
if(resp && !resp.error){
for(var i in resp){
FB.api('/'+resp[i].id+'/photos', function(r){
if(r && !r.error){
for(var n in r){
photoURLs.push(r[n].source);
}
// access photoURLs here
}
}
}
}
}
}
I'm using the following code to get google contacts name and phone number. Authorization page itself is not coming properly it shows error as "The page you requested is invalid". :( pls help me to solve this...
`
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
var contactsService;
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
setupContactsService();
logMeIn();
getMyContacts();
}
function checkLoggedIn(){
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.checkLogin(scope);
if(token != "")
return true;
else
return false;
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
//We load all results by default//
query.setMaxResults(10);
contactsService.getContactFeed(query, handleContactsFeed, ContactsServiceInitError);
}
//Gets the contacts feed passed as parameter//
var handleContactsFeed = function(result) {
//All contact entries//
entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var telNumbers = contactEntry.getPhoneNumbers();
var title = contactEntry.getTitle().getText();
}
}
</script>
<body>
<input type="submit" value="Login to Google" id="glogin" onclick="initFunc();">
</body>`
Thanks
It looks like you are trying to use the Google Contacts 1.X API. That's been deprecated. Look at the JavaScript examples for the Google 3.X API and see if that helps.
You can try this example
var config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", function(response) {
console.log(response);
//console.log(response.data.feed.entry);
});
}
Don't forget to add <script src="https://apis.google.com/js/client.js"></script> into your html file. Good Luck!
I want to read multiple RSS feeds using jQuery.
I'm trying to write a flexible function that will just take the RSS URL and it will output only its TITLE AND IMAGE how to do that for multiple RSS URLs?
The easiest way would be to use the Google AJAX Feed API. They have a really simple example, which suits what you want nicely:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
<div id="feed"></div>
Of course, you can mix jQuery with the API instead of using native DOM calls.
Have you seen this JQuery plug-in: http://plugins.jquery.com/project/jFeed
A little late to the party but I actually did something similar to this using the deviantART gallery feed and displaying the latest thumbnail. I wrapped it up into a couple of functions for easy use:
function keratin_callback(elem, data)
{
if (!data
|| !data.entries
|| data.entries.length < 1
|| !data.entries[0].mediaGroups
|| data.entries[0].mediaGroups.length < 1
|| !data.entries[0].mediaGroups[0].contents
|| data.entries[0].mediaGroups[0].contents.length < 1
|| !data.entries[0].mediaGroups[0].contents[0].thumbnails
|| data.entries[0].mediaGroups[0].contents[0].thumbnails.length < 1) {
$("<span>Data returned from feed not in expected format.</span>").appendTo(elem);
return;
}
var entry = data.entries[0];
$("<img>").attr("src", entry.mediaGroups[0].contents[0].thumbnails[0].url)
.appendTo(elem)
.wrap("");
}
function keratin(elem, url)
{
//keratin written by adam james naylor - www.adamjamesnaylor.com
if (!elem || elem.length < 1) return; //no element found
$.ajax({
//you could use document.location.protocol on the below line if your site uses HTTPS
url: 'http:' + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url + '&cache=' + Date.UTC()),
dataType: 'json',
success: function(data) {
if (!data || !data.responseData) {
return keratin_callback(elem, null);
}
return keratin_callback(elem, data.responseData.feed);
}
});
}
$(document).ready(function() {
keratin($('#da_gallery'), 'http://backend.deviantart.com/rss.xml?q=gallery%3Adeusuk%2F28671222&type=deviation')
});
Full details here: http://www.adamjamesnaylor.com/2012/11/05/Keratin-DeviantART-Latest-Deviation-Widget.aspx