Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Okay so look at these to alert()s. Here is the full code:

function OfficialFacebookLikes(Title)
{
    $.getJSON('https://graph.facebook.com/'+Title, function(data) {
         alert(data['likes'].toString()); //<<temp
         return data['likes'].toString();
    });
}

$(document).ready(function(){
    $('.ui-btn').click(function(){ //cocacola
        var LikeCount = OfficialFacebookLikes("cocacola");
        alert(LikeCount);
    });
});

Why does

alert(LikeCount)

display (which is "undefined" when displayed) before

alert(data['likes'].toString())

I called the function OfficialFacebookLikes before I called the alert(LikeCount). Could someone please explain why this is occurring. If my thought process isn't making since.. I'm use to coding in C++.

share|improve this question

2 Answers 2

up vote 0 down vote accepted

The .getJSON function is asynchronous, this means that it needs a callback to call when it's finished, otherwise you'll never know when the function has been completed. Asynchronous functions run separately from the rest of the code.

When you call OfficialFacebookLikes("cocacola") it will call the .getJSON function. Now the .getJSON functions starts by its own and doesn't stop the script, so right after calling OfficialFacebookLikes("cocacola"), the next line of code is executed, which is actually alert(LikeCount). But LikeCount has not yet been defined, since that .getJSON is still working.

When .getJSON finishes working the callback function given in $.getJSON(..., function() {... }) gets executed, and then the LikeCount variable gets defined. So if you want to alert LikeCount you have to put the alert() inside the callback of .getJSON.

share|improve this answer
    
I will also add that LikeCount is undefined, and will always be so, because there is no return value from the function. The OP's attempt to get a value for LikeCount using this code will always fail, regardless of whether the AJAX has called back or not. –  Thomas W Tupper Aug 2 at 0:36

This is an asynchronous Ajax call. You won't have data available until the call returns. In your document ready code, you are attempting to alert the call immediately.

Instead, do whatever you need to do with the result set in the callback handler of the ajax:

$.getJSON('https://graph.facebook.com/'+Title, function(data) {
         doSomethingWithMy(data);

    });
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.