-2

I am trying to access a variables inside a $.post jquery method. The code I have so far is below:

var fromDatabase;
$.post( "../read.php", function( data ) {

    fromDatabase = JSON.parse(data);

    console.log(fromDatabase); //this works fine
    return fromDatabase; 
});

console.log(fromDatabase); // but this gives me 0.

I am trying to get the from database variable so i tried to declare it outside the function to no avail. Thank you.

Ally Jr
  • 1,055
  • 1
  • 14
  • 27

2 Answers2

0

You can't - you must continue program execution from within the callback, not immediately after the asynchronous $.post call.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

You cannot return from an asynchronous function, that's the nature of asynchronicity. Instead, after your value is available (the callback function is called) you must work with the data within the scope of that function.

Perhaps a good starting point would be some Ajax tutorial. If you want more, simply google for JavaScript async.

Robert Rossmann
  • 11,931
  • 4
  • 42
  • 73