$.ajax({
type: "post",
dataType:"json",
url: "json.php",
success: function(a) {
var test = a.data[0]['id'];
}
});
alert(test); //not working
Asked
Active
Viewed 44 times
0
Cristian Lupascu
- 34,894
- 15
- 87
- 127
firman arif
- 1
- 1
-
what exactly value does it alert eg undefined or anything else – Aatif Bandey Sep 14 '16 at 07:30
-
You need to define test as a global variable – Aatif Bandey Sep 14 '16 at 07:31
-
http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – naortor Sep 14 '16 at 07:31
2 Answers
0
The variable test
is not global defined it won't alert the value.
try this
var test;
$.ajax({
type: "post",
dataType:"json",
url: "json.php",
success: function(a) {
test = a.data[0]['id'];
}
});
alert(test);
Aatif Bandey
- 961
- 8
- 14
-
Also it's asynchronous call it may alert `undefined` because java-script will make an ajax call and move to next statement. – Aatif Bandey Sep 14 '16 at 07:39
0
Your var test
is not global, but also ajax
is asynchronous called , it will alert test to undefined
even if you used global variable
as alert will first execute while ajax is waiting from server response ... so used like below
function test(a) { alert(a); }
$.ajax({
type: "post",
dataType:"json",
url: "json.php",
success: test
});
David Jaw Hpan
- 4,423
- 1
- 22
- 49