0

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?

2 Answers 2

1

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

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

2 Comments

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?
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).
0

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

Comments

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.