views:

44

answers:

2

UPDATE3 and FINAL: SOLVED thanks to Evan and meder!

UPDATE2: I should clarify, I need function updateFilters (a,b) to be called, not created. The function exists elsewhere. Sorry for confusion.

The code below does not work as expected - udpateFilters(a,b) is being called before for loop ends. Changing async to false solves the problem, but this does not seem right. Moreover updateFilters() is called regardless of ajax success.

What did I do wrong?

save (updateFilters(a,b));

function save (cb) {
    $.ajax ({
         url:'save.php',
         data:somedata,
         async:true,
         success: function (response) {
             for (var i in response) {}

             if (typeof cb!='undefined') cb;
    });
}

function updateFilters (a,b) {
//do some stuff here
}

ANSWER: So as meder suggested I change the parameter. This is 2/3 of the answer!

save (
    (function (a,b) {
        return function () {
            return updateFilters(a,b);
        }
    })(a,b)
);

Now change the following:

if (typeof cb!='undefined') cb (); //brackets are important!

And good to go!

+4  A: 

You are passing the invocation of a function, not a function that should be called at a later point. If you want the latter, do this:

save (
   (function(a,b){
      return function() {
        return updateFilters(a,b)
      }
   })(a,b)
);
meder
Thank you! I'm trying to understand the sequence of calls, which function is called when. Can you help?
selytch
Put alerts inside of each function with unique values and when you see those alerts you'll know which functions are called.
meder
that's my issue. alert from the second return is never called.
selytch
i mean putting alert after return function (){alert ('r1');... never appears
selytch
You are now referencing code that no one is able to see. Please post the modified alert code you have.
meder
I see what you created... Sorry for misunderstanding, but function updateFilters already exists, it just needs to be used as callback with set parameters upon completion of ajax.
selytch
+1  A: 

Regarding your update, you never invoke the callback. It's the same as doing

x; // does nothing

You want to call the callback:

cb(); // invoke the function
Evan Trimboli
Thanks! I did not realize importance of parentheses!
selytch