views:

62

answers:

1

Hello!

I want to write a javascript function, that will make an ajax request to PHP script and returns it's result. That's how it looks:

function myjsfunc(some_data)
{
    $.post(
            "/myscript.php",
            { some_data: some_data },
            function(response)
            {
                result = response;
            }
          );
    return result;
}

The problem is, that result is always undefined. This might be because variable result is not in myjsfunc namespace? Or it is because success function result is received way after the main function is processed?

Anyway, how can I get desired result? Is there a way?

+2  A: 

You don't get to return the result because it's not defined by the time your outer function finishes. Your AJAX call is happening asynchronously and the callback function is being called after the POST happens. To deal with your result, you need to do something like this:

function myjsfunc(some_data) {
    $.post("/myscript.php", { some_data: some_data }, function(response) {
            if (some_data.prop) {
                myReturnHandler(response);
            } else {
                myOtherHandler(response);
            }
        }
    );
}

Where you'll define myReturnHandler separately and it will need to know how to take over processing with the result data.

-- EDITED --

You can also perform tests to determine how to handle your response. Added extra code to demonstrate.

g.d.d.c
This would work, except that (from the comment on the question) OP wants to use the function for different purposes. This would only allow one possible code execution for the response.
patrick dw
Not necessarily. Depending on what kind of response bodies he's getting there can be processing logic in myReturnHandler. It can dispatch to other functions based on content, or caller, or some other value he passes in.
g.d.d.c
g.d.d.c - Valid point.
patrick dw
+1 there are lot of people around trying to make "synch calls" with ajax. Ajax stands for ASYNCHRONOUS JavaScript and XML.As g.d.d.c. mentioned you can pass different handlers to the function if you want to apply it for different purposes.
Dani Cricco