3

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;
}
3
  • Use return inside the success callback Commented Mar 29, 2014 at 11:22
  • 2
    It has to do with the fact your AJAX call is asynchronous, your question has also been asked (and answered) a million times, for example here. Commented Mar 29, 2014 at 11:24
  • use async = false in your ajax Commented Mar 29, 2014 at 11:31

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note get_duration() still returns undefined this way.

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.