0

i am using a variable to store json data coming from post method. and when i am using that variable outside of post method it shows its value as undefined. how do i access that variable. here is my code.

 var val;
 $.post("dat/jsondat.php",function(data)
 {

       alert(data);//this alert value
       val = data;
       alert(val);//this alert value
 });
 alert(val);//this alert undefined

the val is a global variable. and i need to use this variable in another function after assigned from post method.

Abhinav
  • 363
  • 4
  • 12
  • just remove `var val;` and try. Without var declaration it will become global so no need to use `var val;` – RJParikh Nov 21 '16 at 06:04

3 Answers3

1

Because you are assigning the variable in an asynchronous function, the code will continue executing to second alert(val) and go back to the callback function until the request is responded. You can access the data by a synchronous request:

$.ajax({  
      url: "dat/jsondat.php",  
      async: false,  //config it here
      success: function(data){  
          alert(val); 
      }  
});

Or just operate your data in the success callback.

Another choice is go to Promise in ES6.

Sparkmorry
  • 99
  • 8
0

set a few miliseconds time out and then alert 'val' like this :

 var val;
 $.post("dat/jsondat.php",function(data)
 {

   alert(data);//this alert value
   val = data;
   alert(val);//this alert value
});

setTimeout(function(){
  alert(val);
  /* other functions */
},200)
farhadamjady
  • 940
  • 6
  • 13
0

Please declare variable as window.var(variable name) before your ajax request and then put ajax response into it and then try to use.. I hope it will help.

Vipin
  • 105
  • 1
  • 2
  • 10