2

this is some basic variable scope question, but I can't figure how to "extract" a variable from a async callback function:

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
    <div id="container"></div>
    <script>

    var API_KEY = "***";
    var USERNAME = "***";
    var res;

        $(
            start()
        );

        function start(){

            $.getJSON(
                "https://www.googleapis.com/youtube/v3/channels",
                {"part": "contentDetails", "forUsername": USERNAME, "key": API_KEY},
                function(data){
                    alert("Success");

                    var s = "";
                    s = data.items[0].contentDetails.relatedPlaylists.uploads;

                    $("#container").html(s);
                    var res = s;
                }
            );

        };
    </script>
</body>

</html>

I've got this code fetching info about a Youtube channel, and I try to put "s" in "res" that is a global variable, but it doesn't works. Is there some way to do it ?

(Also if someone knows a better way to extract data from the response object returned by getJSON, it would be a better idea, but I can't figure that out either...)

Thanks

user3360437
  • 87
  • 1
  • 7
  • `res = s;` remove `var` from sucess callback method – Satpal Mar 19 '15 at 10:14
  • Also, fyi, `$(start());` immediately execute the start function as you are calling it with `()` (not the goal of $(document).ready()) – Hacketo Mar 19 '15 at 10:16
  • Oops, don't know what that "var" is doing here. The thing is it doesn't works anyway. :/ If I remove it and try console.log(res); at the end of start function, it prints "undefined". – user3360437 Mar 19 '15 at 10:25

1 Answers1

-1

update below code.remove var from res in side success function . read more about javascript variable scope HERE

function start(){

        $.getJSON(
            "https://www.googleapis.com/youtube/v3/channels",
            {"part": "contentDetails", "forUsername": USERNAME, "key": API_KEY},
            function(data){
                alert("Success");

                var s = "";
                s = data.items[0].contentDetails.relatedPlaylists.uploads;

                $("#container").html(s);
                 res = s;
            }
        );

    };
Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32