3

So I am trying to shorten an URL with the new V4 Bitly API, but I am getting an JSON error.

My code:

$(function() {
    $(".createBitly").on("click", function(e) {

        e.preventDefault();

        var url = $(this).attr("href");
        var accessToken = "xxx";

        var params = {
            "long_url" : encodeURIComponent(url)            
        };

        $.ajax({
            url: "https://api-ssl.bitly.com/v4/bitlinks",
            cache: false,
            dataType: "json",
            method: "POST",
            contentType: "application/json",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
            },
            data: params
        }).done(function(data) {
            console.log(data);
        }).fail(function(data) {
            console.error(data);
        });

    });
});

Results: a 422 http error;

  "{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}"

But running it with CURL does work though: How to shorten URL using PHP Bitly v4?

What am I doing wrong? Is it not possible with jQuery only?

TIA.

Arjan
  • 193
  • 1
  • 3
  • 9
  • Could it be that the long_url value must be an escaped JS string rather than encoded by applying encodeURIComponent() to it ? The example in the linked case is {"long_url":"https:\/\/stackoverflow.com\/questions\/ask"}. Which would be "https%3A%2F%2Fstackoverflow.com%2Fquestions%2Fask" after encoding. I assume Bitly wants to find slashes so as to process the URL. Interestingly the Bitly API docs say the long_url 'must' be uriencoded, but the answer in the example you link to uses json_encode. – Vanquished Wombat May 03 '19 at 11:38
  • yes it seems you do not send correct json-encoded data – Nikos M. May 03 '19 at 11:43
  • I also tried escape(), no luck. Also tried "https:\/\/stackoverflow.com\/questions\/ask" as a string, no luck either. – Arjan May 03 '19 at 12:29

1 Answers1

1

I had made this edit from your code above and its working well.

1) JSON.stringify before sending request (convert your request to JSON format).

2) No need for encodeURIComponent().

$(function() {
  $(".createBitly").on("click", function(e) {

    e.preventDefault();

    var url = $(this).attr("href");
    var accessToken = "token";

    var params = {
        "long_url" : url           
    };

    $.ajax({
        url: "https://api-ssl.bitly.com/v4/shorten",
        cache: false,
        dataType: "json",
        method: "POST",
        contentType: "application/json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
        },
        data: JSON.stringify(params)
    }).done(function(data) {
        console.log(data);

    }).fail(function(data) {
        console.log(data);
    });
  });
});
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
Bez
  • 26
  • 2