Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)