0

Using jQuery Ajax I am able to get JSON data back from PHP end point. Now on client side I need to store the data on bigger scope level to be used with other function out the scope of Ajac done() and success() functions. so I tried to store the data in tmpdata variable like in success()

success: function (data) {tmpdata = data;  }   

and in .done()

requestdata.done(function (data) {
 tmpdata = data; 
)}

in the code of

//var tmpdata;
let tmpdata;

var requestdata = $.ajax({
...
dataType: "JSON",
success: function (data) {tmpdata = data;  }    
});

requestdata.done(function (data) {
 tmpdata = data; 
)}

function testdata(){
  console.log(tmpdata );
}


$("#data").on("click", function(){
   testdata();
 });

but I am getting this error on running testdata()

Uncaught ReferenceError: tmpdata is not defined

How can I fix this, and what is causing this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • 2
    You are trying to log the data before request has completed. Can't eat a pizza before it gets delivered – charlietfl Sep 07 '19 at 23:19
  • Well look like I didnt explain te situation well. I am not calling the `testdata()` right away after ajax. I am storing calling the method on btn click . please see the update – Behseini Sep 08 '19 at 00:07
  • As you can see this is different case than what you guys pointing as duplicated.I want to save the returned data and use it on another click event in the page – Behseini Sep 08 '19 at 00:09
  • The principles are the same. In the code shown you are trying to access data before request completes...period. If request completes before click event occurs...should be no problem. Nothing shown about such an event – charlietfl Sep 08 '19 at 02:07

0 Answers0