Bilal
Bilal

Reputation: 23

graph.facebook output in a object

I am trying to convert the information I receive Facebook from a Facebook graph request to an object but so far the only thing I did was put all the information in one large string. Is there a better way to put the whole URL in to an object so its accessible like object.Name? This is my javascript code to get the URL code and put it in an object:

var json = $.ajax({
    'url': "https://graph.facebook.com/me?fields=name,email,birthday,location&access_token=xxxxcallback=?"
});

When I say json.responseText I get this output in one string:

'{
   "name": "MY_NAME",
    "email": "MY_EMAIL",
    "birthday": "MY_BIRTHDAY",
    "location": {
        "id": "XXXX",
        "name": "MY_LOCATION"
    },
    "id": "MY_ID"
}'

I need this code to put it on my website for the registration page so that I can access the values easily. What am I doing wrong? Thanks for any help!

Upvotes: 2

Views: 29

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

If you access the response of the AJAX request through any of the standard jQuery methods, such as the success property of $.ajax or done() of the returned deferred object then the responseText will be automatically deserialised for you. Try this:

$.ajax({
    url: "https://graph.facebook.com/me?fields=name,email,birthday,location&access_token=xxxxcallback=?",
    success: function(data) {
       // access the properties of the response here:
       console.log(data.name);
       console.log(data.email); 
       console.log(data.location.name);
    }
});

Also note that Facebook have a Javascript SDK which also provides the above functionality as well as providing some other OAuth helpers. It may be worth looking in to.

Upvotes: 1

Related Questions