Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 271
user3313127 Avatar asked Jun 09 '26 11:06

user3313127


1 Answers

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.

like image 112
Amit Joki Avatar answered Jun 11 '26 01:06

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!