Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitly function returning undefined

I've got a basic function that I'm trying to return a shorten url from bit.ly. My username and api_key have just been removed for this post but they've been tested and I'm getting a correct response with them. We've also checked and we are geting a JSON response with the correct data.

The problem I'm having is that I want this function to be something that we can call at different points on the site to shorten links that will be included in part of a Tweet. So the idea was just to write a function that we could call in time because we specifically know were something will be tweeted from and need to call the url of the page dynamically.

When the url is passed to the function we are getting undefined as the returned value. Here the function:

    var UrltoShorten = 'http://google.com',
        bitly = shortenUrl(UrltoShorten);

    function shortenUrl(longUrl) {

        var username = 'removed',
            key = 'removed';

        $.ajax({
            url: 'http://api.bit.ly/v3/shorten',
            data: { 
                longUrl: longUrl,
                apiKey: key,
                login: username
            },
            dataType: 'jsonp',
            success: function (v) {
                var shortUrl = v.data.url;
                return shortUrl; 
                //console.log(shortUrl); // Will return shorten Url 
            }
        });
    }

console.log(bitly); // Returns undefined 

In our testing we've found that console.logging the value inside of the success function returns the shortened URL every time. Console.logging the value outside of the shortenUrl function returns undefined every time.

Is there a reason we can't get the correct value out side of the function?

like image 656
erik Avatar asked Aug 16 '26 07:08

erik


2 Answers

ajax calls are asynchronous, which means the program will not flow line-by-line like you'd expect. the javascript outside of the ajax call will continue to run, and then the control will jump back to the success/error callbacks when the ajax call finishes in the background.

short answer: anything you want to do with the data from an ajax call must be in the success handler of that call.

if, for some reason, you want to halt everything until the ajax call finishes, then pass ajax the option async: false. This will freeze the browser until the ajax call is complete.

like image 194
jbabey Avatar answered Aug 17 '26 21:08

jbabey


Set ajax synchron using:

 $.ajax({
    async:false,
    ...
})
like image 40
A. Wolff Avatar answered Aug 17 '26 21:08

A. Wolff



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!