1
<script>

        var apikey = "someKey";
        var SEid = "0137454dfgsdfgsdfgzxv4435099:pnqp_fvtmsy";
        var query = "Flower";
        var returnedData;

        $.get("https://www.googleapis.com/customsearch/v1?key=" + apikey + "&cx=" + SEid + "&q=" + query, function(data){

        console.log(data);
        returnedData = data;
        });

        console.log(returnedData.items[1].formattedUrl);
        </script>

I keep getting back the error Uncaught TypeError: Cannot read property 'items' of undefined

but I can't figure out why the variable returned Data is undefined. I'm not trying to even reference it until after I've called the get request.

Please don't flag this question as invalid, I'm really trying to figure this out and have tried for the past 2 days various methods but I just can't figure it out.

brk
  • 48,835
  • 10
  • 56
  • 78
brandenM
  • 29
  • 2
  • 1
    probably shouldn't share an api key – Dan Oswalt Mar 21 '18 at 04:39
  • @brandenM `$.get` makes an asynchronous call which mean we never know when the response will be back & `js` will not wait for it.So `console.log(returnedData.items[1].formattedUrl);` will be executed instead of waiting for the result.When it is executing `returnedData` is undefined because till now no response has arrived from `$.get` call. Please check the duplicate.The problem & solution is clearly defined there.Hope it will be useful – brk Mar 21 '18 at 04:44

2 Answers2

1

The $.get is running asynchronously - once the script reaches that line, it simply sends out the request, it doesn't wait for the request to complete before continuing.

You can't return a value that's generated asynchronously. You could, however, return a promise that, when resolved, resolves with the desired value.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Using returnedData.toJSON().items or just returnedData.get(items).get(0) directly.

Hearen
  • 7,420
  • 4
  • 53
  • 63