0

How I can use count variable out of ajax? In ajax function "count" shows count, but dessous nothing.

var count;
$.ajax({
cache   :   false,
dataType:   'json',
type    :   "POST",
url     :   "count.php",
success  :   function(tdata){
count = tdata;
console.log(count); //this works

}               

});

console.log(count); //this doesn't work
Nitish Kumar Diwakar
  • 663
  • 4
  • 14
  • 25

1 Answers1

1

$.ajax() is async, you need to wait for it to finish.

var count;
$.ajax({
cache   :   false,
dataType:   'json',
type    :   "POST",
url     :   "count.php",
success  :   function(tdata){
    count = tdata;
    console.log(count); //this works

}               

})
.done(() => {
    // this code runs after ajax is resolved
    console.log(count);
});

Refer to http://api.jquery.com/jQuery.ajax/ for other chaining methods

Sean
  • 337
  • 2
  • 7