-2

I have this code :

function retrieve_districts(){

var json='';

$.get("http://localhost/aaa/districts.php",function(result, textStatus) {       
    if(textStatus=="success"){
        json=JSON.parse(JSON.stringify(result)); (alert works fine here)
    }
}, "json");

alert(json);

}

but the alert is empty, how can I do ? thank you very much

Vincent Roye
  • 2,751
  • 7
  • 33
  • 53

3 Answers3

1

Alerting your json, wont work at the bottom of the code. The json variable is not populated until the Ajax call is completed, hence why the alert works fine inside the if statement.

You can put a callback method inside the if statement and call that back once your Ajax query is completed.

Husman
  • 6,819
  • 9
  • 29
  • 47
0

welcome to the wonderful world of asynchronous programming!

you have to move the alert inside the callback function.

you might push you code to behave like synchronous but, I would not recommend it, you will always find yourself struggling against the design.

PA.
  • 28,486
  • 9
  • 71
  • 95
0

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.

David
  • 208,112
  • 36
  • 198
  • 279