0
$.ajax({    
     type: "post",
     dataType:"json",
     url: "json.php",
     success: function(a) {
        var test = a.data[0]['id'];
     }
   });

alert(test); //not working
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137

2 Answers2

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
  • 1,193
  • 11
  • 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
   });
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52