views:

17

answers:

2

Hi,

I have a slow function that does an AJAX request:

function X(param1,param2){
var params={
    type: "POST",
    url: "./ajax/useful.php",
    data: "param1="+param1+"&param2="+param2,
    success: function(msg){
      //do something
    }
  };
  var result=$.ajax(params).responseText;
}

Everything works fine when I call X("asdf","qwerty").

Now, what I want to do is to be able to call function X as follows:

function X(param1,param2,function(){alert('hi');}){
var params={
    type: "POST",
    url: "./ajax/useful.php",
    data: "param1="+param1+"&param2="+param2,
    success: function(msg){
      /////
      //I want to be able call the function in the 3rd parameter (alert in this case)
      /////
    }
  };
  var result=$.ajax(params).responseText;
}

Now you might say why don't I just call alert('hi') directly inside the success. Sure I can do this, but I want to be able to vary what goes on inside the called function (not just a simple alert('hi'), depending on who's calling X.

+2  A: 

You declare your X function like this:

function X(param1,param2,callback){

...use the callback like this:

success: function(msg){
    callback();
}

...and call X like this:

X('a', 'b', function(){alert('hi');});

This works because your success handler is a closure over the data within your X function, including its arguments. It has a live reference to that information (even after X returns), and so later when the Ajax call completes, it can still use the callback argument. More on closures here: Closures are not complicated

T.J. Crowder
Legend, that should work. I wasn't sure of the syntax. Thanks so much,
Eamorr
A: 
function X(param1,param2,f){
var params={
    type: "POST",
    url: "./ajax/useful.php",
    data: "param1="+param1+"&param2="+param2,
    success: function(msg){
      f();
    }
  };
  var result=$.ajax(params).responseText;
}

should work. You can no call X like this:

X(param1,param2,function(){dowhatever})
joni
Hi, thanks for the reply. T.J. Crowder, above, came up with a good way of calling X whilst taking full advantage of anonymous functions.
Eamorr
@Eamorr my code is exactly the same the only difference is that ` callback ` is named ` f ` in my code :)
joni