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

alert(test); //not working
Cristian Lupascu
  • 34,894
  • 15
  • 87
  • 127

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
  • 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