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?

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.