I have that code:
var s, d, p = '';
$.ajax(
{
type: "POST",
url: ajaxurl,
data: {action: "get_info"},
success: function(r)
{
// r contain that json data
// {"s":"long-string","d":"string","p":"string"}
// That served from the server with that header
//
// header('Cache-Control: no-cache, must-revalidate');
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// header('Content-type: application/json');
d = r.d;
s = r.s;
p = r.p;
}
}
);
// And here console return s as undefined
console.log(s);
Any idea on what’s going wrong with that ?
The
$.ajax()call simply starts the ajax operation. The code then falls through to yourconsole.logstatement but the ajax call hasn’t returned yet. Hence the value ofshas not yet been set.At some point later the ajax call returns your results and at that point your call back is fired. So if you want to refer to the value that is returned, you should reference the variable
sinside the callback.The better way to do this is normally like this:
If you really need to, you can reference
soutside of the callback but if you do, you need to put some mechanism in place to make sure thatshas already been initialised (i.e. that your ajax call has already returned). This introduces other complexities such as synchronisation and error handling and can make your program flow rather unreliable.