0
function get_url(){
    var returnValue  = null;
    $.ajax({
        async: false,
        type: "GET",
        url: "http://127.0.0.1:1337/?callback=?&command=get_url",
        dataType: "json",
        success: function(data){
            data = $.parseJSON(data);
            console.log(data[0].get_url); // "not_null"
            returnValue = data[0].get_url;
            }
    });

    console.log(returnValue); // "null"
    return returnValue;
}

Why function don't return "not_null" ?

2

2 Answers 2

2

That is because your ajax method is so call it another thread. Once you call it your method will continue, but value will be set once ajax call is done. So you can wait, this is bad solution but it can help:

function get_url(){
    var returnValue  = null;
    var _done = false;
    $.ajax({
        async: false,
        type: "GET",
        url: "http://127.0.0.1:1337/?callback=?&command=get_url",
        dataType: "json",
        success: function(data){
            data = $.parseJSON(data);
            console.log(data[0].get_url); // "not_null"
            returnValue = data[0].get_url;
            _done = true;
            }
    });
    while(!_done) { }
    console.log(returnValue); // "null"
    return returnValue;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Whats quiet clever. Never thought of that.
I think Andreas's solution of callbacks is much cleaner, rather than resorting to while(!_done) { }
2

You can't return the value from your ajax request. Because return is returning returnValue at once and not waiting for the ajax request.

If you want to receive the ajax response you can use a callback method:

function get_url(callback){
    var returnValue  = null;
    $.ajax({
        async: false,
        type: "GET",
        url: "http://127.0.0.1:1337/?callback=?&command=get_url",
        dataType: "json",
        success: function(data){
            data = $.parseJSON(data);
            console.log(data[0].get_url); // "not_null"
            returnValue = data[0].get_url;
            callback(returnValue);
        }
    });
}

And then call:

get_url(function(response) {
    console.log(response);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.