0

I want to create a separate function to get specific data from Facebook graph JSON. For example, I have the load() and called getNextFeed() function.

The getNextFeed works correctly. Except that returning value of aString is not successful. When I pop alert(thisUrl). It said undefined.

Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.

    function load()
    {

         $(document).ready(function() {
         var token = "AccessToken";
         var url = "https://graph.facebook.com/me/home?access_token=" + token;      
          var thisUrl = getNextFeed(url);
         alert(thisUrl); // return undefined
    });




    function getNextFeed(aUrl)
    {   
          $.ajax({
           type: "POST",
           url: aUrl,
           dataType: "jsonp",
           success: function(msg) {
           alert(msg.paging.next); // return correctly

            var aString = msg.paging.next;
            alert(aString); // return correctly
            return aString;

           }
        });
     }
ns_sky
  • 3
  • 2
  • possible duplicate of http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery – Nakul Nov 05 '11 at 10:47
  • @Nakul: thanks. It is useful link. Solved mine through Deferred() – ns_sky Nov 05 '11 at 11:56

1 Answers1

0

The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.

You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.

Example:

function load()
    {

         $(document).ready(function() {
         var token = "AccessToken";
         var url = "https://graph.facebook.com/me/home?access_token=" + token;      
         getNextFeed(url);
         alert('Please wait, loading...');
    });




    function getNextFeed(aUrl)
    {   
          $.ajax({
           type: "POST",
           url: aUrl,
           dataType: "jsonp",
           success: function(msg) {
           alert(msg.paging.next); // return correctly

            var aString = msg.paging.next;
            alert(aString); // return correctly
            do_something_with(aString);

           }
        });
     }
Alex Schenkel
  • 728
  • 1
  • 7
  • 13