Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook Graph API getting JSON using Ajax

This is my first time using Facebook in jQuery.

I'm getting the following error:

Uncaught SyntaxError: Unexpected token : 
www.facebook.com/feeds/page.php?id=20531316728&format=JSON
    &callback=jQuery110105899784066714346_1383828332964&_=1383828332965:2

Code

$.ajax({
    url: 'http://www.facebook.com/feeds/page.php?id=20531316728&format=JSON',
    dataType: 'jsonp'
}).done(function(data) {
    alert(data);
});

JSFiddle

Why am I getting this?

like image 295
Okky Avatar asked Nov 07 '13 13:11

Okky


1 Answers

Why doesn't it work?

jQuery, being a Javascript framework, must apply the implementation rules for Ajax requests, more specifically the Same-origin policy one. Briefly, this restriction says that Ajax requests can only be performed towards the same domain.

This information can also be found in the jQuery $.ajax documentation:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

Workaround

YQL: Yahoo Query Language

The Yahoo Query Language is an expressive SQL-like language that lets you query, filter, and join data across Web services. With YQL, apps run faster with fewer lines of code and a smaller network footprint.

Source: http://developer.yahoo.com/yql/

Using YQL as a proxy

YQL can be used as a proxy in order to make a cross-domain Ajax call possible. Explanations can be found here: JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls

Code

var fbUrl = "http://www.facebook.com/feeds/page.php?id=20531316728&format=JSON";

$.ajax({
    url: "http://query.yahooapis.com/v1/public/yql",
    dataType: "jsonp",
    data: {
        q: 'select * from json where url="' + fbUrl + '"',
        format: "json"
    },
    success: function (data) {
        $.each(data.query.results.json.entries, function (i, v) {
            $('#entries').append(data.query.results.json.entries[i].title + '<br />');
        });
    }
});

jsFiddle here

like image 120
Stéphane Bruckert Avatar answered Oct 29 '22 18:10

Stéphane Bruckert