user3313127
user3313127

Reputation: 93

Return variable from Javascript function

I can`t return result of this function.

function get_duration() {
    var a = '';
    $.ajax({
        url: "http://gdata.youtube.com/feeds/api/videos?q=3KMz3JqRByY&max-results=50& format=5,1,6",
        dataType: "jsonp",
        success: function (data) {
            re2 = /seconds='(\d+)'/ig;
            while (re.exec(data) != null) {
                a = re2.exec(data);
            }
        }
    });
    return a;
}

Upvotes: 3

Views: 70

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

You have to use return inside the success callback since, A in Ajax is asynchronous.

Like this:

function get_duration() {
    var a = '';
    $.ajax({
        url: "http://gdata.youtube.com/feeds/api/videos?q=3KMz3JqRByY&max-results=50& format=5,1,6",
        dataType: "jsonp",
        success: function (data) {
            re2 = /seconds='(\d+)'/ig;
            while (re.exec(data) != null) {
                a = re2.exec(data);
            }
            return a;
        }
    });
}

But, this function isn't guaranteed to return. You'll have to use a callback function kind of thing.

Upvotes: 1

Related Questions