0

I tried to call bit.ly API using this jQuery script:

$.get('http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=www.wordpress.com', function(data) {
    alert(data);
});

but firebug said "405 Method Not Allowed". What's wrong? Thanks a lot.

Rendicahya
  • 4,205
  • 7
  • 36
  • 56

5 Answers5

6

As mentioned already, standard AJAX call do not work cross domain. Just use JSONP with $.getJSON() instead.

Here is an example how to get a shortened URL with Bitly API and jQuery:

function get_short_url(long_url, login, api_key, func)
{
    $.getJSON(
        "http://api.bitly.com/v3/shorten?callback=?", 
        { 
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": long_url
        },
        function(response)
        {
            func(response.data.url);
        }
    );
}

The following code could be used to get a short URL:

/*
Sign up for Bitly account at
 https://bitly.com/a/sign_up

and upon completion visit
https://bitly.com/a/your_api_key/ 
to get "login" and "api_key" values
*/
var login = "LOGIN_HERE";
var api_key = "API_KEY_HERE";
var long_url = "http://www.kozlenko.info";

get_short_url(long_url, login, api_key, function(short_url) {
    console.log(short_url);
});
Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55
3

$.get do not support cross-domain GET.

You can use JSONP technique, and $.getJSON.

BTW, http:// should in the longUrl parameter of bit.ly API call. But it's not the main problem.

iamamac
  • 9,632
  • 4
  • 35
  • 30
1

The reason you're seeing the 405 error is because you're violating the Same Origin Policy, which prevents retrieving data from a different domain, subdomain, or protocol.

Gaurav Gupta
  • 5,380
  • 2
  • 29
  • 36
0

The URL is not valid.

You have to put the http:// in front of the longUrl argument.

Edit

Some clarifications:

This url http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=http://www.wordpress.com returns

{ "errorCode": 0, "errorMessage": "", "results": { "www.wordpress.com": { "errorCode": 1206, "errorMessage": "URL you tried to shorten was invalid.", "statusCode": "ERROR" } }, "statusCode": "OK" }

this one: http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=http://www.wordpress.com returns

{ "errorCode": 0, "errorMessage": "", "results": { "http://www.wordpress.com": { "hash": "j1IP3", "shortKeywordUrl": "", "shortUrl": "http://bit.ly/6i1NkN", "userHash": "6i1NkN" } }, "statusCode": "OK" }
Loïc Wolff
  • 3,205
  • 25
  • 26
-1

They probably expect a POST request rather than a GET.

Azeem.Butt
  • 5,855
  • 1
  • 26
  • 22