The alert is empty because the value of json
is ''
when you execute the alert.
AJAX is, by design, asynchronous. So while it's technically possible that it may complete before another line of code that follows it (though it's highly unlikely in this example), it's not guaranteed. When an AJAX request is launched, it continues in another thread and the rest of the inline code continues immediately without waiting for the AJAX request to complete.
So in order to do anything in response to your AJAX request, you need to do it in the callback function:
function retrieve_districts(){
var json='';
$.get("http://localhost/aaa/districts.php",function(result, textStatus) {
if(textStatus=="success"){
json=JSON.parse(JSON.stringify(result));
alert(json);
}
}, "json");
}
That function which gets passed into the get()
function is the callback and will be executed after the AJAX request completes.