0

I'm having problems with JavaScript and especially with a variable:

var totalrec = {};
        $http.get('url').
        success(function(data, status, headers, config) {
                totalrec = data;
                //here it all works
                console.log(data);
                }).
        error(function(data, status, headers, config) {
               .....
                });
        //here it prints an empty object
        console.log(totalrec);

I receive a JSON string from an external server. When I print it to the console.log in the success function it works. But I need arguments from the JSON string outside the function. If I print it to the console.log outside the function it prints an empty object.. Who can help me?

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • Your data object is only accessible in the scope of the success function and error function not outside. – Sachacr Jun 05 '15 at 12:59
  • You assigned `data` to `totalrec`. Why do you need `data`? – SomeShinyObject Jun 05 '15 at 12:59
  • 1
    Shouldn't you print `totalrec` outside the function? `data` is only visible wihtin the anonymous success function. But you already put the data in a global var... – Wa Kai Jun 05 '15 at 12:59
  • Suggest reading this: http://www.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/ – SomeShinyObject Jun 05 '15 at 13:00
  • Sorry. I meant printing totalrec outside the function.. typo. It also doesn't work if I print totalrec. And i need data since the JSON string is in data, right? – Rubinho092 Jun 05 '15 at 13:06

0 Answers0