Google Ajax search API - javascript

I'm wondering, is it possible to receive google results over their own ajax API in a way like, 100 results per page?
Without a visible search field, I'd like to get the results in the background to create a progression for some search phrases.
My basic question is, what are the restrictions of the google search api ?
--update--
is it possible to change language for a search with google api ? From the start on, it
just delivers from .com in english
Kind Regards
--Andy

The largest number of results you can get is 64, 8 per page of the searcher.
It is possible to combine all of these into one page, but it involves the searcher making 8 calls to the Google Ajax Search API.
Further, you will need to create your own function to render the results:
var s;
var page = 1;
google.load('search', '1', {'nocss' : true});
google.load('jquery', '1.4.2'); // optional
google.setOnLoadCallback(function() {
// T&C's state you should display branding, create a <div id="branding"></div>
google.search.Search.getBranding(document.getElementById('branding'));
s = new google.search.WebSearch();
s.setResultSetSize(google.search.Search.LARGE_RESULTSET);
s.setSearchCompleteCallback(this, searchComplete, null);
s.setNoHtmlGeneration();
});
function searchComplete() {
if(s.results && s.results.length > 0) {
var results = s.results;
for(var i = 0; i < results.length; i++) {
var result = results[i];
// render the results
}
if(page < 8) {
s.gotoPage(page);
page++;
}
}
}
For information about how to render your results see: http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GwebResult
To change the language, add the hl argument when including the script in web pages:
<script src="http://www.google.com/jsapi?hl=en" type="text/javascript"></script>

http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GSearchControl
This has information about the main controller class used. It appears that the following answers your question about result size:
.setResultSetSize(switchTo)
This method is called to select the
number of results returned by each of
the searchers. Note, this is not a
scalar. It is an enumeration that
indicates either a small number of
results, or a large number of results.
In the future, this method may be
enhanced to support medium and extra
large result sets. From the sample
applications, you have probably seen
the more/less twiddle control at the
top of the search control. This method
is used by that twiddle control.
switchTo - supplies en enumeration
which indicates the desired number of
search results to return for each
configured searcher. Valid values
include:
google.search.Search.LARGE_RESULTSET -
request a large number of results
(typically 8 results)
google.search.Search.SMALL_RESULTSET -
request a small number of results
(typically 4 results)
google.search.Search.FILTERED_CSE_RESULTSET
- request up to 10 results. This will only work for Web Search queries
scoped to a Filter Custom Search
engine, otherwise an error will be
returned. returns - n/a

Here is my code:
<script src="https://www.google.com/jsapi?key=GOOGLE_SEARCH_KEY" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load("search", "1");
function OnLoad() {
// Create a search control
var searchControl = new google.search.SearchControl();
var options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
searchControl.addSearcher(new google.search.WebSearch(),options);
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
// Tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));
}
google.setOnLoadCallback(OnLoad);
//]]>
</script>
<style>.gsc-control { width: 80%; } input.gsc-search-button { border: 1px solid black; }</style>

Related

Read get request parameter with javascript

I want to create a script that highlights every instance of a string on a page and that string is received as a get request paramater. I want my page to link to the script like: <script src="../Scripts/highlightSearch.js" defer></script> and inside that script I want to have a function like function highlight(content) {...} where content is the string that I want to be highlighted throughout the page. How can I acess content via my script?
In terms of "reading the GET request" there is a relatively new API available that makes reading the querystring parameters trivial. This particular API is URLSearchParams
If you refer to the compatability table at the bottom you'll notice that Internet Exploder does not support this API so, as a possible alternative, you can use quite a simple function to process the querystring yourself. This following function could ( relatively ) easily be modified to provide similar methods to those found in the URLSearchParams api - alternatively search for a Polyfill
const getArgs=function() {
let o={};
location.search.substring(1).split('&').forEach( function( n ){
let l=n.indexOf('=');
if( ~l )o[ n.substring( 0, l ) ]=unescape( n.substring( l + 1 ) );
});
return o;
};
With those in place when you need to read / mainpulate the querystring you can fork the logic
if( 'URLSearchParams' in window ){ /* use methods available to/within the "URLSearchParams" api */ }
else {
let args=getArgs();
let query=args.hasOwnProperty('keyword') ? args.keyword ? false;
if( query ){
let res=RegExp(pattern[, flags]);
/* etc */
}
}
That should, I hope, help give a baseline with which to accomplish the stated goal - there are other ways open to you young Jedi. Good luck.

How to perform functions on two different domains?

This is the algorithm of what I want to do:
1.Locates flickr links with class' high_res_link and puts them in array [].
2.Opens flickr link with extension "sizes/h/"
3.finds largest photo dimensions on flickr. Then goes to that link. Or if there arent any big enough goes to step 2 and goes to next
array.
4. then opens link to download if downloading is enabled. If not goes to step 2 and goes to next array.
5. Goes to step 2 and goes to next array.
I am trying to write some code that crosses two domains: Tumblr and Flickr.
I have currently written 3 functions with Jquery and Javascript which I want to run on 2 different URLs:
Function #1:
function link_to_flickr() {
var hre = [];
$('.high_res_link').parent(this).each(function(){
var h = $(this).attr('href') +"sizes/o/";
hre.push(h);
});
alert(hre[0]);
}
This finds the links on the Tumblr page to the Flickr pages I want. And puts them in an array.
Function #2:
function find_large_quality() {
var w = 1280;
var h = 720;
var matchingDivs = $("small").each(function () {
var match = /^\((\d+) x (\d+)\)$/.exec($(this).text());
if (match) {
if (parseInt(match[1], 10) >= w && parseInt(match[2], 10) >= h) {
return true;
}
}
return false;
});
var href = $.trim(matchingDivs.text()).match(/\(.*?\)/g);
if (matchingDivs.length >= 1) {
alert("success");
} else {
alert("fail");
}
var ho = $('small:contains("'+href[href.length - 1]+'")').parent(this).find("a").attr("href");
alert("http://www.flickr.com"+ho);
}
This function once on the Flickr URL then searches for an image with dimensions greater than 720p.
Function #3:
function Download(){
var heyho = $('a:contains("Download the")').attr('href');
window.open(heyho, '_blank');
}
This downloads the image file. Once on the Highest quality Flickr URL
Each alert I want to open the URL instead. And perform the next function on. I have been trying for ages and ages of a method to go about doing something like this.
Using AJAX, using PHP, using Jsonp, using jquery.xdomainajax.js, etc... But I can't come up with a sufficient method on my own.
Has anybody got any way they would recommend going about doing something like this?
You usually can't run functions on different domains due to CORS unless the domains allow that.
If you're writing a userscript/extension, what you can do is use postMessage (quick tutorial on how to use it cross-domain) on both pages in a content script and use the achieved inter-page communication to control your script flow.
An alternate method is to use the APIs of the websites you want to access.
Or use Python with BeautifulSoup.

Auto-refresh Javascript For RSS Using Google Feed API

I apologize if the title is trash. What I'd like to do is rather simple in concept... but I'm having a bit of trouble.
I would like to automatically refresh an RSS feed that is displayed using Google Feed API. I haven't worked with the Google Feed API before, but it seemed like a quick option for getting this rolled out. Technically, it only needs to be the content part that is reloaded.
The purpose: This is displaying the results of a poll, refreshing them every 3 seconds (it will be displayed in a presentation.) The actual result is in the 'content', whereas the item being voted on is the 'title'.
The unstyled basics of the code:
<script type="text/javascript">
var feedcontainer=document.getElementById("feeddiv");
var feedurl="http://theurl.com";
var feedlimit=100;
var rssoutput="<b>Latest Results:</b><br /><ul>";
function rssfeedsetup(){
var feedpointer=new google.feeds.Feed(feedurl) //Google Feed API method
feedpointer.setNumEntries(feedlimit) //Google Feed API method
feedpointer.load(displayfeed) //Google Feed API method
}
function displayfeed(result){
if (!result.error){
var thefeeds=result.feed.entries
for (var i=0; i<thefeeds.length; i++)
rssoutput+="<li>" + thefeeds[i].title + "<br />" + thefeeds[i].content + "</li>"
rssoutput+="</ul>"
feedcontainer.innerHTML=rssoutput
}
else
alert("Error fetching feeds!")
}
window.onload=function(){
rssfeedsetup()
}
</script>
I'm not sure how to go about making the results refresh every 3 seconds. I've tried a few things, like "How to autorefresh XML in Javascript" but wound up printing the results multiple times on the page.
Major bonus points for anyone that can point me towards turning it into an auto refreshing bar graph. That will be my next search or question on here.
I think you should call rssfeedsetup() in a setInterval function. Something like
window.onload = function() {
var delay = 3000;
rssfeedsetup();
setInterval(rssfeedsetup, delay);
}

Google custom search for images only

Since Google image search API is deprecated, one should use Google custom search API for this.
I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'hu'});
google.setOnLoadCallback(function() {
var customSearchOptions = {
enableImageSearch: true,
imageSearchOptions: {
layout: google.search.ImageSearch.LAYOUT_CLASSIC
}
};
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
customSearchControl.setAutoCompletionId('XXX');
customSearchControl.draw('cse', options);
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
The API documentation is quite poor, it only describes how to add additional results.
Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.
searchType = "image"
See this post on the cse blog.
EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.
Per the Google Custom Search Element Control API - documentation web site, this is possible.
https://developers.google.com/custom-search/docs/element
This is the fragment used for searching by image by default:
'defaultToImageSearch'
So I believe the full syntax for using this would be:
<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:
/**
* #param {string} searchTerm - Search term for Google Image search.
* #param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* #param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
function getImageUrl(searchTerm, callback, errorCallback) {
// Google image search - 100 searches per day.
// https://developers.google.com/image-search/
// var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
// '?v=1.0&q=' + encodeURIComponent(searchTerm);
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.image.thumbnailLink;
var width = parseInt(firstResult.image.thumbnailWidth);
var height = parseInt(firstResult.image.thumbnailHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.
I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).
I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.
And yes, it's total BS that Google has provided such lousy support for this API. =)
Try adding this line:
customSearchOptions['disableWebSearch'] = true;
I tried to get a more authoritative answer in the official Google AJAX APIs group,
and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.
check this
Try this one
customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;

How does paging in facebook javascript API work?

I'm trying to recover the last week posts in my facebook news feed with the javascript sdk.
I'm able to get the first page but then, I don't know how to continue iterating through the other pages. I've tried it with the following code:
$('#loadPosts').bind('click', function() {
FB.api('/me/home',{since:'last week'}, getPosts);
});
getPosts = function(response){
for (element in response.data){
post = response.data[element]
console.log(post);
}
previousPage = response.paging.previous;
console.log(previousPage);
// can i call FB.api(previousPage, getPosts); ??
}
But I'm getting a URL as previous page and I don't know how to make a javascript FB.api call from that URL. Any ideas?
Alright, it seems a lot of whining about a simple issue that I still believe my old answer clarifies. Anyway, let me babysit you. :)
First: I find out that you cannot really go to the "previous" page from the first page. Ideally, I should. So, here is a bug that I have filed you may want to follow: https://developers.facebook.com/bugs/391562790938294?browse=search_50fcac3ce094e7068176315
Second: If this is by design, you cannot go back to "previous" from the first page (because there is no previous), but you can surely go to "Next". However, since the API behaves as a cursor, and you have moved forward, now your "previous" page would work.
The answer to the question:
I'm getting a URL as previous page and I don't know how to make a javascript FB.api call from that URL. Any ideas?
yes, you can make FB.api call. But I suggest you to make a HTTP GET call instead, because it's easier. Also, note that previous may return and empty array like {"data":[]}
How to get previous/next page?
Here, I am writing a small code that uses jQuery. In case you do not want to read the code, there are two ways:
Use previous/next URL and make HTTP GET request. Which, if not empty, will come with next set of "previous", "next" link.
Parse the URL, and get the query-string as JSON ans pass it to FB.api. I used jQuery BBQ pluging for parsing.
Important Note: In the example, I am using "next" URL because on the first request if I use "previous" it gives empty JSON instead of giving posts from the past. However, I can use use "previous" URL once I have moved ahead a few pages. Like Google results, you can not go previous on page 1, but you can from any page > 1 (see Example 3 below). This is called pagination.
Example 1: Code using HTTP GET (preferred): (I will load 3 posts/page and look three next-pages)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="https://raw.github.com/cowboy/jquery-bbq/master/jquery.ba-bbq.min.js"></script>
<script>
var i =0;
var getPosts = function (response){
for (element in response.data){
post = response.data[element]
console.log(post.id + ": " +post.message);
}
// can i call FB.api(nextPage, getPosts); ??
if(i < 2){
nextPage = response.paging.next;
console.log(nextPage);
i++;
//Method 1: I use it.
$.get(nextPage, getPosts, "json"); //optional: $.getJSON can be use instead
}
}
$(document).ready(function(){
$('#loadPosts').bind('click', function() {
FB.api('/me/home',{since:'yesterday','limit': '3'}, getPosts);
});
})
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'XXXXXXXXXXXX', // FILL YOUR APP ID HERE!
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
});
// Additional initialization code such as adding Event Listeners goes here
};
</script>
<button id="loadPosts">Load Posts</button>
<p>Please open developer console to see what's happening. In Firefox, you can use ctrl+shift+k, and in Chrome/Chromium use ctrl+shift+i</p>
</body>
</html>
Response:
100004192352945_156620584487686: undefined
137723270230_10152423499430231: On this day, please spare a thought for those fellow citizens, for whom I just spare a thought and do nothing else.
642965867_10151211036740868: Thanks everyone for their wishes! The wishes made my day!
https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD&until=1359184568
367116489976035_536776529676696: Rage. Quit. Life.
899605553_10152450871820554: undefined
367116489976035_417820828298092: undefined
https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD&until=1359179890
137723270230_10152423148745231: Pratibha Patil used to love the Republic Day Parade, especially the part where the visiting Chief Guest extended her an invitation to visit his/her own country.
137723270230_10152423131700231: The Kingfisher tableau at Republic Day Parade was so simple. Vijay Mallya riding a bicycle.
367116489976035_484460034950769: undefined
Example 2: Code using FB.api: (I will load 3 posts/page and look three next-pages)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="https://raw.github.com/cowboy/jquery-bbq/master/jquery.ba-bbq.min.js"></script>
<script>
var i =0;
var getPosts = function (response){
for (element in response.data){
post = response.data[element]
console.log(post.id + ": " +post.message);
}
// can i call FB.api(nextPage, getPosts); ??
if(i < 2){
nextPage = response.paging.next;
console.log(nextPage);
i++;
//Method 2: If you have to call FB.api
var params = jQuery.deparam.querystring(nextPage);
console.log(JSON.stringify(params, null, 2));
FB.api('/me/home', params, getPosts)
}
}
$(document).ready(function(){
$('#loadPosts').bind('click', function() {
FB.api('/me/home',{since:'yesterday','limit': '3'}, getPosts);
});
})
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'XXXXXXXXXXXX', // FILL YOUR APP ID HERE!
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
});
// Additional initialization code such as adding Event Listeners goes here
};
</script>
<button id="loadPosts">Load Posts</button>
<p>Please open developer console to see what's happening. In Firefox, you can use ctrl+shift+k, and in Chrome/Chromium use ctrl+shift+i</p>
</body>
</html>
Response:
367116489976035_536776529676696: Rage. Quit. Life.
899605553_10152450871820554: undefined
367116489976035_417820828298092: undefined
{
"limit": "3",
"access_token": "AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD",
"until": "1359179890"
}
137723270230_10152423148745231: Pratibha Patil used to love the Republic Day Parade, especially the part where the visiting Chief Guest extended her an invitation to visit his/her own country.
137723270230_10152423131700231: The Kingfisher tableau at Republic Day Parade was so simple. Vijay Mallya riding a bicycle.
367116489976035_484460034950769: undefined
https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD&until=1359178140
{
"limit": "3",
"access_token": "AAACYjXGS5FQBAIR3brc2LibjBcZCi2kRJUybG8VMaaJSZARQ8SzNE7BE4PBrDIFVZB0AaVEa1dZCpX1fhCvoD2rnq8uc8OGaIFhO9uvVXAZDZD",
"until": "1359178140"
}
655515199_403590309726450: a good resolution to take on Republic Day
505588854_496901583686790: Love the secret world that slow motion reveals.
693811975_10151217837201976: undefined
Example 3: Performing: page1 -> page2 -> page1 or page -> next -> previous The following code will load page1, then go to "next" page (page2), then come back to page1, using "previous"
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="https://raw.github.com/cowboy/jquery-bbq/master/jquery.ba-bbq.min.js"></script>
<script>
var i =0;
var getPosts = function (response){
for (element in response.data){
post = response.data[element]
console.log(post.id + ": " +post.message);
}
// can i call FB.api(nextPage, getPosts); ??
if(i < 2){
nextPage = response.paging.next;
if(i==1)
nextPage = response.paging.previous;
console.log(nextPage);
i++;
$.get(nextPage, getPosts, "json"); //optional: $.getJSON can be use instead
}
}
$(document).ready(function(){
$('#loadPosts').bind('click', function() {
FB.api('/me/home',{since:'yesterday','limit': '3'}, getPosts);
});
})
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'XXXXXXXXXXXX', // FILL YOUR APP ID HERE!
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
});
// Additional initialization code such as adding Event Listeners goes here
};
</script>
<button id="loadPosts">Load Posts</button>
<p>Please open developer console to see what's happening. In Firefox, you can use ctrl+shift+k, and in Chrome/Chromium use ctrl+shift+i</p>
</body>
</html>
Response:
PAGE1:
367116489976035_536806916340324: How big is the Solar System?
Full infographic here: http://bit.ly/WmzfVn
137723270230_10152423534790231: "Sociologist" Ashis Nandy has claimed that most of the corrupt came from OBC/SC/ST castes.
Following this, Corrupt people have strongly condemned Nandy's attempts to divide them on caste lines. They'll be united in loot, forever.
100004192352945_156620584487686: undefined
PAGE2:
https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAKqIMyCVYjH9upK4e2bjUwLoVbbFDL0ffc0SZBTVR9MUFGV4ZCq6HBdFIadFMpLDC3ATMZCJ4GPsXWpG4qTGODavuvzLAZDZD&until=1359185659
137723270230_10152423499430231: On this day, please spare a thought for those fellow citizens, for whom I just spare a thought and do nothing else.
642965867_10151211036740868: Thanks everyone for their wishes! The wishes made my day!
367116489976035_536776529676696: Rage. Quit. Life.
PAGE1:
https://graph.facebook.com/677811901/home?limit=3&access_token=AAACYjXGS5FQBAKqIMyCVYjH9upK4e2bjUwLoVbbFDL0ffc0SZBTVR9MUFGV4ZCq6HBdFIadFMpLDC3ATMZCJ4GPsXWpG4qTGODavuvzLAZDZD&since=1359185123&__previous=1
367116489976035_536806916340324: How big is the Solar System?
Full infographic here: http://bit.ly/WmzfVn
137723270230_10152423534790231: "Sociologist" Ashis Nandy has claimed that most of the corrupt came from OBC/SC/ST castes.
Following this, Corrupt people have strongly condemned Nandy's attempts to divide them on caste lines. They'll be united in loot, forever.
100004192352945_156620584487686: undefined
OLD ANSWER
Use limit, offset, since and until parameters to achieve your goal.
Refer: http://developers.facebook.com/docs/reference/api/
Paging
When querying connections, there are several useful parameters that enable you to filter and page through connection data:
limit, offset: https://graph.facebook.com/me/likes?limit=3
until, since (a unix timestamp or any date accepted by strtotime): https://graph.facebook.com/search?until=yesterday&q=orange
The following should get all the posts since last week until yesterday from 21st - 30th message (basically, third page of 10 message per page pagination).
FB.api(
'/me/home',
{
'since':'last week',
'limit': '10',
'offset': '20',
'until': 'yesterday'
},
getPosts
);
I've just tested, it works. I have used limit=4, which is page-size kind of thing. So, when I fetch data since Feb 02, 2011 (Unix Time Stamp: 1296626400) till today using this
https://graph.facebook.com/me/home?access_token=[AUTH_TOKEN]&since=1296626400&limit=4
It returns the data, plus it also return URL to go to next page
{
"data": [
<ARRAY OF POSTS HERE>
],
"paging": {
"previous": "https://graph.facebook.com/me/home?access_token=[NEW_AUTH_TOKEN]&since=1298026753&limit=4",
"next": "https://graph.facebook.com/me/home?access_token=[NEW_AUTH_TOKEN]&limit=4&until=1298023222"
}
}
You can safely use previous and next attributes of the JSON object to jump to next page (or previous page). This seems to be the easiest way to do.
By the way, \u00257C needed to be converted to | to get this to work.
If you simply wanted to get the next page (using the paging.next object) you could do a jQuery.getJSON request. Something like the following:
function loadAlbums(){
FB.api('/me/albums', function(response){
handleAlbumsResponse(response);
});
}
function handleAlbumsResponse(response){
var albums = response.data;
for( var i in albums){
var album = albums[i];
$('#albums ul').append('<li>' + album.name + '</li>');
}
if( response.paging.next){
console.log('fetching next page...');
$.getJSON(response.paging.next, function(response){
handleAlbumsResponse(response);
});
}
}
The key constraint in your question is we can't use the 'next' url provided in the response.
I'll try to answer your question by first asking a more general question:
How can we create a user experience for our Facebook app where every call for more items returns the same amount of items.
If the user requests 'more' and gets 10 items, presses 'more' and gets then 4, then 7 etc, she might think our app is buggy.
On the Open Graph intro page, different parameters for paging are introduced. These are:
limit
offset
until
since
as mentioned under the 'paging' heading. However if we implement a solution with limit and offset where we increment offset ,e.g.:
https://graph.facebook.com/me/home?limit=10&offset=OFFSET
where OFFSET will be increased by the limit each request, we find that the number of results returned will sometimes not be equal to the “limit” parameter we specified. This is because parameters are applied on Facebook's side before checking if the queried results are visible to the viewer. We ask for 10, but we might get 8 items in return.
This means we can't use a solution where we increment limit and offset if we want our app's 'more' request to always return the same amount of items.
A solution proposed in this blog by Jeff Bowen (who works on the Facebook plaform team) is this logic:
request item with limit = YOUR_LIMIT.
retrieve the created_time field of the last item in the response.
request next 10 items with since = RETRIEVED_CREATED_TIME and limit=YOUR_LIMIT
Here's a code sample, based on an example in the blog post mentioned above:
var graphURL = "https://graph.facebook.com/me/home?" +
"callback=processResult&" +
"date_format=U&" +
"limit=10";
function loadPosts() {
var script = document.createElement("script");
script.src = graphURL;
document.body.appendChild(script);
}
function processResult(posts) {
if (posts.data.length == 0) {
document.getElementById("loadMore").innerHTML =
"No more results";
}
else {
graphURL = graphURL + "&until=" +
posts.data[posts.data.length-1].created_time;
for (var post in posts.data) {
var message = document.createElement("div");
message.innerHTML = posts.data[post].message;
document.getElementById("content").appendChild(message);
}
}
}
This solution retrieves the next 10 items from the user's newsfeed in chronological order without using the url in the JSON response.
It's working
function friends_list()
{
for (var x = 0; x<500; x++)
{
FB.api(
'/me/friendlists/',
'GET',
{"fields":"id","offset":x},
function(response) {
for (i = 0; i < response.data.length; i++)
{
document.getElementById("friends_list").innerHTML =
document.getElementById("friends_list").innerHTML + "<br>" + response.data[i].id;
}
document.getElementById("friends_list").innerHTML =
document.getElementById("friends_list").innerHTML + "<br>" ;
}
);
}
}
I noticed the question is very old. My answer is true for the these days FB jsSDK (2017) :)
Actually it's simpler than what predecessors described and somewhat intuitive. FB jsSDK it is an API itself and it is expected to be able to navigate through pages of the response by itself and using same means, no?
function getPosts(){
FB.api('/me/posts', 'GET', {limit:250}, cbGetPosts);
}
function cbGetPosts(response){
// do your stuff with response.data
if(response && response.paging){
FB.api(response.paging.next, cbGetPosts); // yep, is this simple
}
}
Obviously this will request for next pages as long as there is a next key defined but s proving the concept.

Categories

Resources