4

I started using jQuery and ajax to get data from database, but i cant find out how i can save result of $.get() into variable outside callback function.

This is my jquery script:

var result="";     
$.get("test.php", function(data){ result=data; });
alert(result);

This is test.php script:

echo "Hello, World";

Every time i run this script it alerts "".

pastx
  • 117
  • 3
  • 4
  • 9

2 Answers2

5

Try this:

var result = "";
$.get("test.php", function (data) {
    SomeFunction(data);
});

function SomeFunction(data) {
    result = data;
    alert(result);
}
palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

Your alert will get fired before the $.get can return any data.

Make the alert run on an event instead - such as a click:

var result="";     
$.get("test.php", function(data){ result=data; });
<span onclick="alert(result);">show alert</span>
fredrik
  • 6,483
  • 3
  • 35
  • 45
  • This works, thank you very much. Can you please explain me why i cant content of jquery script insert into $(document).ready(function(){}); Because when i do, it does not work. – pastx Apr 12 '13 at 06:53
  • Because the ajax request is asynchronous. Meaning it can take any amount of time to finish and `$.get` will return immediately, but your code assumed that the `$.get` call had fetched the result of `test.php` call before returning. – fredrik Apr 12 '13 at 08:01