The following is my code:
$.post(
"index.php?component=static_content&action=rules_count",
{ region:rname,page_url:page_url},
function(data1) {
alert(data1);
var num = $(data1).find('.ruleNum').html();
}
);
alert(num);
But on line alert(num); there is an error num is undefined. Any idea what I am doing wrong?
Help much appreciated.
you declared the variable
numinside your post callback, so outside that function the variable is clearly undefinedBut even if you define it outside, its value won’t be displayed as you expected, since ajax is asynchronous (so that, when you alert the variable the ajax call is still running)
if you need to acces num even outside just call another function passing the variable, e.g.
or use
Deferred Objects(since ajax methods return a promise sincejQuery 1.5) you can also do