0

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?

3
  • What is the result being used for? Commented Sep 1, 2010 at 15:54
  • 1
    possible duplicate of Can't get correct return value from an jQuery Ajax call Commented Sep 1, 2010 at 15:55
  • result is being used in many other functions for different purposes, so I need to return the data, not just put it in some HTML tag or anything. Commented Sep 1, 2010 at 15:56

1 Answer 1

5

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.

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

3 Comments

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.
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.
+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.

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.