-3

I'm using dajaxice to retrieve a json attribute - that I would like to be global. I'm not sure why my global var is always "undefined":

var recent_id;
$(function(){
    recent_id = Dajaxice.ticker.get_home_timeline(get_home_timeline_callback);
        alert(recent_id);
    });

function get_home_timeline_callback(data){
    if(data==Dajaxice.EXCEPTION){
        alert('Error! Something happens!');
    }else{
          var parsed = JSON.parse(data.home_timeline);
          var parsed_id = {'parsed_id':parsed[0].id_str};
          console.log(parsed_id);
    }
    return parsed_id;    
}

@dajaxice_register
def get_home_timeline(request):
    home_timeline = oauth_req(
    'http://api.twitter.com/1/statuses/home_timeline.json?count=1',
    settings.TWITTER_TOKEN_KEY,
    settings.TWITTER_TOKEN_SECRET
    )
    return simplejson.dumps({'home_timeline': home_timeline })

Is this a bad way to access a var to be used in another ajax function?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
neridaj
  • 2,143
  • 9
  • 31
  • 62

2 Answers2

0

Seems like async issue. Modify your get_home_timeline_callback function as following

function get_home_timeline_callback(data){
    if(data==Dajaxice.EXCEPTION){
        alert('Error! Something happens!');
    }else{
          var parsed = JSON.parse(data.home_timeline);
          var parsed_id = {'parsed_id':parsed[0].id_str};
          console.log(parsed_id);
    }
    //debug
    alert(parsed_id);
    //since the value has come, now assign it to the global variable
    recent_id = parsed_id;    
}
Anand
  • 14,545
  • 8
  • 32
  • 44
  • I already tried that and when the global var recent_id is accessed out of the get_home_timeline() function scope it is still undefined. – neridaj Jan 10 '12 at 20:37
0

It seems like the variable scope issue. The scope of the variable parsed_id is declared within the else statement within the { }, so its scope is within the else statement. And when you return the parsed_id outside the brackets it might be giving undefined.

Go through the scope of variables explanation here

Change your function as shown below.

function get_home_timeline_callback(data)
{
    var parsed_id = "";
        if(data==Dajaxice.EXCEPTION)
        {
            alert('Error! Something happens!');
        }
        else
        {
              var parsed = JSON.parse(data.home_timeline);
              parsed_id = {'parsed_id':parsed[0].id_str};
              console.log(parsed_id);

        }
        return parsed_id;
}

Now here the scope of the variable parsed_id can be accessed anywhere within function. Hope this solves your problem if not sorry. This was my assumption that the scope might be affected.

Community
  • 1
  • 1
AmGates
  • 2,127
  • 16
  • 29