iff
iff

Reputation: 192

jquery ajax, getJSON gives null

I have a function with it i want to get value from a php file:

var phrases = null;
function setPhrases(lang) {
    $.getJSON(locationHostname()+'json?json=lang&lang='+lang,
            function(json) {
        phrases = json;
        alert( 1 + ' ' + phrases);//phrases = [object Object]
    });
    alert( 2 + ' ' + phrases);//phrases = null
}
setPhrases('en');
alert(3+' '+phrases);//phrases = null

how to set correctly it, that alert(3+' '+phrases); gets an object instead of null? I want to use the function that e.g returns the value from getJSOn.

Thank you

Upvotes: 1

Views: 109

Answers (4)

Vince V.
Vince V.

Reputation: 3143

you should use a callback method. the problem with your getJSON method that it's async.

example:

function setPhrases(lang, callback) {
    $.getJSON(locationHostname()+'json?json=lang&lang='+lang,
            function(json) {

        callback(json);
    });
}

   setPhrases('en',function(result) {

    alert(result);

});

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

I think you can't get phrases in third alert() due to asynchronous behavior of $.getJSON().

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

You can't. .getJSON runs asynchronously, and unless it's lightning fast, the alert(2) and alert(3) will run before it completes. You need to have the alert(2) and alert(3) as part of the success function, or use a Deferred.

EDIT: I guess since it's electronic it probably is lightning fast, and even that's not enough!

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

$.getJSON is asynchronous , that's why you get undefined: the alerts are executed while ajax call is still running

You could call a function on success event, passing the json as argument, e.g.

function setPhrases(lang) {
    $.getJSON(locationHostname()+'json?json=lang&lang='+lang,
        function(json) {
            continueProcessing(json)
        }
    );
}

function continueProcessing(obj) {
  ...
}

Upvotes: 2

Related Questions