up vote 0 down vote favorite

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?

link|flag

2 Answers

up vote 1 down vote accepted

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);.

link|flag
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 Jun 2 at 18:37
1  
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 Jun 2 at 18:50
up vote 0 down vote

Well, I did sorta the solution provided by Alxandr. It turns out if I want the result, I'll have to implement a callback, but in order to not care about the result I just call the ActionProxy with the first two arguments and check if the callback function is present like so:
function ActionProxy(action, input, callback){

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

}

I would've expected an error calling a three-argument function with two arguments. Oh well - javascript is a strange language. :)

link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.