views:

37

answers:

2

Hi!
In order to make function calls to our back-end php code we've implemented something called an ActionProxy like this:

function ActionProxy(action, input, callback){  
    $.post("ActionProxy.php?method="+action, 
        { data: input},   
            function(data, textStatus, XMLHttpRequest){
                        //return data.ResponseWhatever
                        }
});

The problem we're having is that using data outside the ActionProxy is impossible due to variable scope limitations (we assume), setting
var res = data.ResponseWhatever
or
return data.ResponseWhatever

is pretty futile. How would one handle these responses most appropriately so that functions calling the actionproxy can access the response values?

+1  A: 

You could use window.ResponseWhatever = data.ResponseWhatever, however, this is not the smartest thing to do. What you want is to do something like this:

function ActionProxy(action, input, callback){
    $.post("ActionProxy.php?method="+action, {data:input},
        function(data, textStatus, xhr){callback(data);});
}

Note: I'm no jQuery-guru, so I might have gotten some of the jQuery-parts wrongly, but the point is that where you want to call return data you instead call callback(data);.

Alxandr
We actually thought of that as well, but given we don't always want a callback we would sometimes like to just receive the return value. Is it at all possible, or is this the way one "is supposed" to write it?
nillls
You cannot use `return` as long as the call is asynchronous, and you really don't want to do a synchronous request due to it being a blocking operation (in many browsers even the UI freeze).
Sean Kinsey
A: 
nillls