javascript – How do I display the short URL from a Bitly API call?

javascript – How do I display the short URL from a Bitly API call?

The problem is that youre not using $.getJSON correctly. Since that is an asynchronous call, the string is not stored in a variable synchronously. Instead, you need to do your follow-up work in a callback function.

$(#shorten).click(function () {
    $encodedTrackedURL = encodeURIComponent($trackedURL);
    var params = {
        access_token: $accessToken,
        longUrl: $encodedTrackedURL,
        format: json
    };

    $.getJSON(https://api-ssl.bitly.com/v3/shorten, params, function (response, status_txt) {
        $(#displayURL).text(status_txt +   + response.data.url);
    });
});

In addition, youll want to take a closer look at the documentation for /v3/shorten to understand the return value properly. Notice that it actually returns a JSON object, with the url value being the short URL. You can also specify format: txt and get the short URL (in string form) as the entire response.

EDIT: I misunderstood the API docs. Looks like the response object contains metadata at the outer level (such as a bit.ly status text, not the same as the HTTP response text) and then an inner data object should contain the real data. I couldnt get it to work due to lacking an access token, but go ahead and try the above. (Updated JSFiddle)

javascript – How do I display the short URL from a Bitly API call?

Leave a Reply

Your email address will not be published. Required fields are marked *