8

I want to retrieve information from my Stack Overflow profile as JSON using the API.

So I use this link http:/api.stackoverflow.com/1.0/users/401025/.

But when I make the request I get a file containing the JSON data. How do I deal with that file using Ajax?

Here is my code (http://jsfiddle.net/hJhfU/2/):

<html>
 <head>
  <script>
   var req;

   getReputation();

   function getReputation(){
      req = new XMLHttpRequest();
      req.open('GET', 'http://api.stackoverflow.com/1.0/users/401025/');
      req.onreadystatechange = processUser;
      req.send();
   }

   function processUser(){       
       var res = JSON.parse(req.responseText);
       alert('test');      
   }
  </script>
 </head>

The alert is never fired and req.responseText seems to be empty. Any ideas?

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

3 Answers3

10

Note: You cannot use Ajax to access another domain. (This is called the same-domain policy.)

However, the StackOverflow API supports JSONP callbacks, so here is a solution:

Load in the script via a <script> tag.

Create a function that does just that:

function load_script(src) {
   var scrip = document.createElement('script');
   scrip.src = src;
   document.getElementsByTagName('head')[0].appendChild(scrip);
   return scrip; //just for the heck of it
}

Set up the callback function:

function soResponse(obj) {
   alert(obj.users[0].reputation);
}

Load it!

load_script('http://api.stackoverflow.com/1.0/users/401025/?jsonp=soResponse');
Community
  • 1
  • 1
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
1

For any future readers:

I wanted to get my Reputation without using oAuth and a whole library to do so. Thanks to Sebastien Horin's answer I easily could using the following:

function get_reputation() {
    const xhttp = new XMLHttpRequest();
    const url = 'https://api.stackexchange.com/2.3/users/USER_ID?&site=stackoverflow';

    xhttp.open( "GET", url );
    xhttp.send();

    xhttp.onreadystatechange = function() {

        if(xhttp.readyState == 4 && xhttp.status == 200) {
            
            var json = JSON.parse(xhttp.responseText);
            
            console.debug( json );
            
        }       
    }
}

get_reputation();

Note: this uses API v2.3.

odil-io
  • 180
  • 9
0

there is a new API ( replace USER_ID )

https://api.stackexchange.com/2.2/users/[USER_ID]?&site=stackoverflow
Sebastien Horin
  • 10,803
  • 4
  • 52
  • 54