ExyTab
ExyTab

Reputation: 557

How can I return value from $.Ajax function?

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" ?

Upvotes: 0

Views: 120

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47137

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);
});

Upvotes: 2

Senad Meškin
Senad Meškin

Reputation: 13756

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;
}

Upvotes: 2

Related Questions