www.webdeveloper.com
Results 1 to 2 of 2

Thread: JSON question: Variable set inside results is not defined for use outside JSON call

  1. #1
    Join Date
    Feb 2006
    Location
    Toronto
    Posts
    105

    JSON question: Variable set inside results is not defined for use outside JSON call

    Hi, I've got this:

    Code:
                     var noteCount = "";
                     jsonRequest('media.getFiles', params,
    		    function(result)     {  noteCount = result['totalCount']},
    		    function(exception)  { noteCount = "0"},
    		    true
    		  );
    The console returns results['totalCount'] with a value of 2 (that's correct).

    When I call noteCount for display, it shows nothing. Neither the var set by result or exception.

    Is this expected behaviour?

  2. #2
    Join Date
    Dec 2005
    Posts
    2,984
    You didn't show us all of your code, so it's impossible to tell. But I'm betting that your actual code (and I could be wrong, please correct me if I am) looks something like this:

    Code:
    var noteCount = "";
                     jsonRequest('media.getFiles', params,
    		    function(result)     {  noteCount = result['totalCount']},
    		    function(exception)  { noteCount = "0"},
    		    true
    		  );
    
     console.log(noteCount);
    At which point, the expected behaviour would be for the console to log an empty string.

    This is because jsonRequest is (again I'm assuming here) probably set to asynchronous (perhaps the third parameter - true - means it's an asynchronous request?).

    So, what happens in your code is the following:
    1. set a new variable noteCount to an empty string.
    2. create a new jsonRequest object with callback functions when the data is returned
    3. While the jsonRequest object is awaiting the data, log the current value of noteCount (an empty string) to the console
    4. The jsonRequest has probably returned data by now so call one of the callback functions


    If the value of noteCount is important for you to continue, then you can only 'do' other things when noteCount data has been successfully returned.

    There's one of two ways to do this - make the request synchronous (not good, 'freezes' the current JS script) or, request the next step in your application in your jsonRequest callback function.

    Hopefully I didn't make this explanation too confusing.
    I've switched careers...
    I'm NO LONGER a scientist,
    but now a web developer...
    awesome.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles