0

I try to manipulate a variable inside a function. But it seems to forget the values once I exit the function, eventhough the variable is declared outside the function.

The essential code:

var posts = {};                

            // Perform a data request
            // skjutsgruppens-page
            $.oajax({
                url: "https://graph.facebook.com/197214710347172/feed?limit=500",
                    *SNIP*
                    success: function(data) {
                    $.extend(posts, data);
                }
            });


            // Gruppen
            $.oajax({
                url: "https://graph.facebook.com/2388163605/feed?limit=500",
                *snip*
                success: function(data) {
                    $.extend(posts, data);
                }
            });

The oajax retrievies data from facebook. I want to make a variable that contains the data from both oajax methods.

The actual code: http://eco.nolgren.se/demo/resihop/#

1
  • This just got a lot stranger... It seems asthough the extend-method only applies when I reload the page. Wtf? Commented Jun 5, 2012 at 23:07

1 Answer 1

2

The issue is likely that the success function executes at an arbitrary time in the future--unless you specifically access posts after you know the success function has executed, you will receive undefined results, completely dependent on function and access timing.

The best approach is to handle this correctly by doing necessary work inside in the success function, or use something like jQuery's .when function.

Sign up to request clarification or add additional context in comments.

6 Comments

You are correct, success executes when I get an answer. that's when I want to extend posts with data. Is that not what I'm doing?
@KristofferNolgren You tell us--in the success function, after you call extend, is the data in the object? Is the data in a format suitable for use by .extend? At what point are you accessing posts and the data is not there?
it seems to be there as though the data in posts is the data from the last loading of the page, and it alternates between the two objects. I really don't understand this...
@KristofferNolgren Alternates between what two objects? When do you make the Ajax calls? When do you access the data in posts outside of the Ajax calls? You need to update your question with more details, IMO.
@KristofferNolgren Ah, gotcha--glad you worked it out. You might consider creating your own answer and accepting it, since mine was way off-base, or editing mine with the additional information.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.