Question: ```
$.post("../js.php", {state: state},
                            function(data) {
                                return data;
                        });

```

Here's my jquery code. Like you can see it sends a post request to js.php.

Here's the code for js.php.

```
{...}
$query = "SELECT * FROM table WHERE x='" . $y . "'";

$result = $mysqli->query($query);

$num_rows = $result->num_rows;

echo $num_rows ? $num_rows : 0;

```

Now, when I alert the "data" back in the js file then it displays fine. But when trying to return it or assign it to a variable it does not work. The console tells me that the variable that has been assigned the value of data is undefined.

Any thoughts?

Updated code:

```
var data = null;

$.post("../js.php", {state: state},
function(response) {
data = response;
});

console.log(data);

```

Still not working. :(

Answer: 
The callback you pass to asynchronous methods such as `$.post` are executed some time in the future, once the async call has returned. The JavaScript execution has moved on and is now somewhere else, so there is nowhere for your callback to `return` to.

Imagine it like this:

```
//Some code... executed as you would expect
var data; //Currently undefined

$.post("../js.php", {state: state}, function(response) {
    //Callback is executed later, once server responds

    data = response; //No good, since we already executed the following code
    return response; //Return to where? We have already executed the following code
});

/* More code... we carry on to this point straight away. We don't wait for
   the callback to be executed. That happens asynchronously some time in
   the future */

console.log(data); //Still undefined, callback hasn't been executed yet

```

If you need to work with the data returned by the async call, do so in the callback.
The example you posted will do nothing EVERY TIME because AJAX calls like this are ASYNCHRONOUS (that's what the **A** in AJAX stands for).

If you want to be able to use the value of the output, add a hidden element to your page with a unique ID that contains the value. Then you can access that element through javascript.