Silver Light
Silver Light

Reputation: 45902

JQuery ajax request inside a function: how to return the value I got?

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?

Upvotes: 0

Views: 3434

Answers (1)

g.d.d.c
g.d.d.c

Reputation: 47978

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.

Upvotes: 5

Related Questions