-3

I'm having problem using variables outside a $.get function, the variable isn't found and the script stops.

What can I do?

$.get("../ajax.php", function (data) {
    var json = JSON.parse(data);
    test = json['jquery']['test'];
});

alert(test)

UPDATE: (This solved my problem) I get the json with $.get. And pass it to my function and the json will be able to get later in the script.

$.get("../ajax.php", function (data) {
function(data) {                    
    loadApp(data);
});

function loadApp(data) {    
    json = JSON.parse(data);                
}
Kim
  • 1,128
  • 6
  • 21
  • 41

1 Answers1

0

Since it's a asynchronous call, all processing will have to be made in the callback function. Put your alert(test) inside the callback function instead.

EDIT:

$.get("../ajax.php", function (data) {
    var json = JSON.parse(data);
    test = json['jquery']['test'];

    alert(test); // Needs to be processed in this scope
});

This occurs since the JavaScript processor reads line by line, detects the ajax-call and sends it, it then jumps to the alert, which will try to alert a non-existing variable. Even if you declare it gobally it wont work; since the AJAX-return is asynchronous, and will therefore be executed in parallel to the other code.

Eric
  • 18,532
  • 2
  • 34
  • 39