0

the duplicate question referred tells us how to use ajax/post calls. my question is how to use the data returned by the anonymous function.

i am using the jquery POST method to get some data from mysql. the call is:

$.post("/php/practice.php",{cat:catname}, function(xdata) {
    qdata=JSON.parse(xdata);
});

this is working fine and i get my required array, qdata.

so, i can access qdata if i do the following:

$.post("/php/practice.php",{cat:catname}, function(xdata) {
    qdata=JSON.parse(xdata);
    alert(qdata[0][0]);
});

qdata is a 2-D array with 140 rows and the values are all there

but if i try to use qdata outside this post, qdata comes up as 'undefined'. eg

$.post("/php/practice.php",{cat:catname}, function(xdata) {
    qdata=JSON.parse(xdata);
});
alert(qdata[0][0]);

if i place the alert outside the post call i get nothing.

how do i get around this problem?

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Wild Beard Dec 16 '16 at 16:01

1 Answers1

1

Your problem is that qdata only exists with the scope of your function.

Either instatiate the qdata variable outside the function

var qdata

$.post("/php/practice.php",{cat:catname}, function(xdata) {
        qdata=JSON.parse(xdata);
});

or let's say you wanted to pass this data to another function that does something with it. you could do this:

$.post("/php/practice.php",{cat:catname}, function(xdata) {
        qdata=JSON.parse(xdata);
        myFunction(qdata);
});

function myFunction(data){
 alert(data[0]);
}
Brad
  • 8,044
  • 10
  • 39
  • 50
  • even if he insantittiate the qdadata outside it aint matter much amigo –  Dec 16 '16 at 16:08
  • Care to elaborate? – Brad Dec 16 '16 at 16:09
  • you said `Either instatiate the qdata variable outside the function` and `or let's say you wanted to pass this......blahblah `. The former is not required or matters or will change any outcome. The latter is the correct answer –  Dec 16 '16 at 16:13