Take the 2-minute tour ×

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)
            { some_data: some_data },
                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?

share|improve this question
What is the result being used for? –  Nick Craver Sep 1 '10 at 15:54
possible duplicate of Can't get correct return value from an jQuery Ajax call –  Quentin Sep 1 '10 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. –  Silver Light Sep 1 '10 at 15:56
add comment

1 Answer

up vote 4 down vote accepted

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) {
            } else {

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.

share|improve this answer
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. –  user113716 Sep 1 '10 at 16:16
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 Sep 1 '10 at 16:20
g.d.d.c - Valid point. –  user113716 Sep 1 '10 at 16:37
+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 Sep 1 '10 at 18:45
add comment

Your Answer


