2

I have a function that is not returning a value the way I would like it to. What the function does is get information that is echoed from a PHP page (the PHP page has an SQL query) and return it. Here it the code:

function getValues(var1,var2) {
  $.post("http://url/to/file.php", {var1:var1,var2:var2}, function(data) {
    values = data.split(',');
    return values[0];
  });
}

I know that the PHP file is working because if I were to write alert(data); or alert(values); I can see the values there. When I call the function, for example, var result = getValues(5,6); result is undefined. Maybe it is because they are not in a list or an array? Help appreciated, thanks.

3
  • 2
    You can't return out of a parent scope by returning out of a child scope. Secondly, in your given code, the $.post success is executed long after getValues returns. The structure used here simply won't work in an asynchronous nature. Commented Aug 14, 2012 at 15:48
  • did you intend values to be a global variable? Commented Aug 14, 2012 at 15:50
  • Thanks, didn't see that thread. Commented Aug 14, 2012 at 15:54

2 Answers 2

4

Because AJAX calls are asynchronous (first A of AJAX), and thus it executes a callback function, it does not return a result.

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

Comments

1

As KayKay points out, the async method will never return any data. However, if you really must have that return, you could set 'async' to false.

2 Comments

As long as you plan on never upgrading jQuery past 1.8
Ah, I did not realize they planned on removing the async parameter. Good to know, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.