Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the new facebook graph api, ajax calls returns null (empty)

Im trying out the new graph api for facebook. I'm trying to fetch some data using jquery ajax. This is a sample of my javascript code, very basic...

var mUrl = 'https://graph.facebook.com/19292868552';
   $.ajax({
        url: mUrl,
        dataType: 'json',
        success: function(data, status) {
          $('#test').html(data);
          alert(data);

      },
      error: function(data, e1, e2) {
        $('#hello').html(e1);  
      }
   });

The url is to a page that does not need access tokens (try it using a browser), but the success function returns an empty object or null.

What am I doing wrong? Thankful for all help!

like image 283
Chris Sunderland Avatar asked Jun 29 '10 07:06

Chris Sunderland


2 Answers

I have covered this and asked this question before. I made a quick tutorial which covers exactly this and explains it all.

In short: JSON is not made for cross domain usage according to its same-origin policy. However the work around is to use JSONP which we can do in jQuery using the supported callback parameter in facebook's graph api. We can do so by adding the parameter onto your url like

https://graph.facebook.com/19292868552?callback=?

by using the callback=? jQuery automatically changes the ? to wrap the json in a function call which then allows jQuery to parse the data successfully.

Also try using $.getJSON method.

like image 80
Stefan P Avatar answered Oct 06 '22 00:10

Stefan P


I was trying to do something similar, in testing I was able to get a working result which I saved on jsFiddle: http://jsfiddle.net/8R7J8/1/

Script:

var facebookGraphURL = 'https://graph.facebook.com/19292868552';
$.ajax({
    url: facebookGraphURL,
    dataType: 'json',
    success: function(data, status) {
      $( '#output' ).html('Username: ' + data.username);
    },
    error: function(data, e1, e2) {
      $( '#output' ).html(e2);
    }
})

HTML:

<html>
  <body>
    <div id="output">BorkBorkBork</div>
  </body>
</html>

Hope that helps! :)

like image 41
AllStruck Avatar answered Oct 05 '22 23:10

AllStruck