2

After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.

function pageFan()
{
    FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
        showAlert(response);
    });
}

function showAlert(response)
{
    if (response == true) {  
        return 'like the Application.';
    } else {
        return "doesn't like the Application.";
    }
}

var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
Eron Venter
  • 21
  • 1
  • 5

2 Answers2

1

This question has already been answered.

Relevant Javascript:

$(document).ready(function(){
      FB.login(function(response) {
      if (response.session) {

          var user_id = response.session.uid;
          var page_id = "40796308305"; //coca cola
          var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
          var the_query = FB.Data.query(fql_query);

          the_query.wait(function(rows) {

              if (rows.length == 1 && rows[0].uid == user_id) {
                  $("#container_like").show();

                  //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

              } else {
                  $("#container_notlike").show();
                  //and here you could get the content for a non liker in ajax...
              }
          });


      } else {
        // user is not logged in
      }
    });
Community
  • 1
  • 1
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
0

That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.

function showAlert(response)
{
    if (response == true) {  
        document.getElementById('debug').innerHTML = 'like the Application.';
    } else {
        document.getElementById('debug').innerHTML = "doesn't like the Application.";
    }
}
Etienne Perot
  • 4,764
  • 7
  • 40
  • 50