-1

If I do the following it gives me, in console.log, the values I want.

        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
                console.log(q);
            });

But if I do this

        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
            });

        console.log(q);

q has no value and is an undefined value? Why can't I set returnedData as public?

Draken
  • 3,134
  • 13
  • 34
  • 54
diedaaf
  • 63
  • 1
  • 1
  • 5
  • `$.get` is an asynchronous call, i.e. it will fire the request and immediately continue on executing the next statements, which in your case is `console.log(q)`. It's clear that your `console.log(q)` is being called way before a response is even returned from the server – Matias Cicero Jun 06 '17 at 14:14

2 Answers2

0

$.get is asynchronous. You are logging before the ajax is able to finish. In other words, the var q will only have the value once the $.get receive the response from the service.

You should handle the returnedData inside the callback function. Or delegate to another function if it's too complex, like:

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
        function(returnedData){
            doStuffWithReturnedData(returnedData);
        });
Smaniotto
  • 404
  • 4
  • 16
-1

Your $.get() is asynchronous.

To get around that, try setting a Promise.

Zenoo
  • 12,670
  • 4
  • 45
  • 69