Ajay Malik
Ajay Malik

Reputation: 329

Can't get Json data using http request

I'm trying to get share_count data for page https://graph.facebook.com/?ids=http://backlinko.com Here my code:

<div id='demo'/>
<script>
  var fbsrc = "https://graph.facebook.com/?ids=http://universalmanual.com";
  var request = new XMLHttpRequest();
request.open('GET', fbsrc, true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
    document.getElementByID('demo').innerHTML+=data.share.share_count;
  } 
};



request.send();
</script>

Upvotes: 0

Views: 42

Answers (2)

vibhor1997a
vibhor1997a

Reputation: 2376

Apart from the typo in document.getElementById you also need to correct how you are accessing the share_count. You need to access it as data['http://universalmanual.com'].share.share_count

<div id='demo'/>
<script>
  var fbsrc = "https://graph.facebook.com/?ids=http://universalmanual.com";
  var request = new XMLHttpRequest();
request.open('GET', fbsrc, true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
    document.getElementById('demo').innerHTML+=data['http://universalmanual.com'].share.share_count;
  } 
};



request.send();
</script>

Upvotes: 0

RahulB
RahulB

Reputation: 2110

The call seems to work fine and the output is coming. You have a typo-

document.getElementByID('demo').innerHTML+=data.share.share_count;

It should be

document.getElementById('demo').innerHTML+=data.share.share_count;

Also the response is coming in below json format -

{
   "http://universalmanual.com": {
      "share": {
         "comment_count": 0,
         "share_count": 0
      },
      "og_object": {
         "id": "477708298951135",
         "type": "website",
         "updated_time": "2013-04-02T05:16:14+0000"
      },
      "id": "http://universalmanual.com"
   }
}

So share count is available in

data["http://universalmanual.com"].share.share_count 

Updated codepen - https://codepen.io/anon/pen/oqowZN

Upvotes: 1

Related Questions