Jeff
Jeff

Reputation: 4003

Ajax call to Github API fails

So I'm a little new at this, a the code I have so far is not working yet, but if anyone can tell me what i missing I would be grateful.

Basically, I'm trying to make a call to github's api, which returns json data. I'd eventually like to parse it and display only specific information, but at the present I'm just trying to get the data to show in my browser. Here is what I have so far:

<script type="text/javascript">
$(document).ready(function() {

$.ajax({
    url: "https://api.github.com/repos/VonC/gitolite/git/refs/tags",
    dataType: "jsonp", // I'm under the impression i should use jsonp, since this is a cross domain call
    success: function (returndata)
    {
        $('.result').html(returndata);
        alert('Load was performed.');
      }  
    });
 });
</script>

The url definitely works: when you call it using CURL, the following json data is returned:

[
{
"object": {
  "type": "commit",
  "sha": "9accde83842523e18de320fc2f0a8efeaebef27b",
  "url": "https://api.github.com/repos/jeffreycwitt/jeffswebpage/git/commits/9accde83842523e18de320fc2f0a8efeaebef27b"
 },
"url": "https://api.github.com/repos/jeffreycwitt/jeffswebpage/git/refs/heads/master",
"ref": "refs/heads/master"
 } 
]

Thanks for any advice you can give me.

Upvotes: 3

Views: 5101

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47280

the returned data is not html, its a json object you have to reference the fields directly or loop through them.

You can access the data like so (although worth noting that using property name object is rather confusing, it can be any string))

returndata[0].object.sha

(And change jason to json)

Upvotes: 1

Tam&#225;s
Tam&#225;s

Reputation: 48041

dataType should probably be jsonp and not jasonp. Even better, it should simply be json as you are not making a JSONP call.

Another thing you should watch out for is that returndata is going to be the actual, parsed JavaScript object that comes out of the JSON representation, not the JSON object as a string. This means that you cannot put it straight into the .result div.

The following seems to work for me:

$.ajax({
    url: "https://api.github.com/repos/VonC/gitolite/git/refs/tags",
    dataType: "json",
    success: function (returndata)
    {
        $("#result").html(returndata[0]["object"]["sha"]);
        alert('Load was performed.');
    }  
});

Upvotes: 5

Related Questions