5

I am trying to implement the Google URL shortener API with the help of jQuery by making an AJAX call. I have done something like this:

$(function() {
    $('#btnshorten').click(function() {    
        var longURL = $('#tboxLongURL').val();

        $.ajax({
            url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: '{ longUrl: "' + longURL +'"}',
            dataType: 'json',
            success: function(response) {
                var result = eval(response); // Evaluate the J-Son response object.
            }
         });
    }); 
});

But it is generating an error in IE. It is showing "Access is denied" and in Firebug it is showing "405 method not allowed." Am I doing something wrong here?

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Mac
  • 6,991
  • 8
  • 35
  • 67

3 Answers3

17

In Javascript, here are 2 ways to to implement the Google URL shortener API:

METHOD #1: Using jsonlib, http://call.jsonlib.com/jsonlib.js Try it out here: http://jsfiddle.net/Qh4eR/

var longUrl = "http://google.com";
document.write("Long Url: "+longUrl);

function googlurl(url, cb) {
  jsonlib.fetch({
    url: 'https://www.googleapis.com/urlshortener/v1/url',
    header: 'Content-Type: application/json',
    data: JSON.stringify({longUrl: url})
  }, function (m) {
    var result = null;
    try {
      result = JSON.parse(m.content).id;
      if (typeof result != 'string') result = null;
    } catch (e) {
      result = null;
    }
    cb(result);
  });
}
googlurl(longUrl , function(s) { document.write("<BR>Short Url: "+s); });

METHOD #2: Using the google client library, https://apis.google.com/js/client.js, Try it out here: http://jsfiddle.net/pPHKe/2/

//var apiKey = 'YOUR_API_KEY';
//gapi.client.setApiKey(apiKey);
var longurl = 'http://www.google.com/';

gapi.client.load('urlshortener', 'v1', function() {
    var request = gapi.client.urlshortener.url.insert({
        'resource': {
            'longUrl': longurl
        }
    });
    var resp = request.execute(function(resp) {
        if (resp.error) {
            $("#show").html('Error. ' + resp.error.message);
        } else {
            $("#show").html("Short URL for "+longurl+" is: " + resp.id);
        }
    });
});
DougA
  • 1,213
  • 9
  • 17
5

Indeed you are, I'm afraid. You can't make cross-domain ajax calls because of browser security.

I know that Ext JS offer a ScriptTagProxy object which can do the work, but I'm not sure if jQuery has anything similar.

An alternative would be to create a kind of "proxy" server-side script on your own host, which could accept parameters from your ajax call, make an HttpWebRequest or similar to googleapis.com and output the response to be picked up again by your ajax call. Then just modify your ajax url parameter to call your new proxy script instead of googleapis. In other words - let the server-side do the cross domain request.

ndtreviv
  • 3,473
  • 1
  • 31
  • 45
  • what server side language are you using? – ndtreviv Jan 14 '11 at 12:25
  • 2
    Maybe I should make myself clearer: Change your ajax call to request a server-side script on your own domain, passing appropriate parameters. Create this server side script to accept parameters, make an HttpWebRequest or similar to googleapis.com, and then output the response, which would be picked up by your jQuery ajax call and eval-ed in the success function you've already defined. Is that clear? I've updated the answer accordingly – ndtreviv Jan 14 '11 at 12:28
  • how come i'm able to load via **$.getJson** the data from other domains _ie_ [twitter](https://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter&count=8&callback=jsonp1298412308011)? – Anyul Rivas Feb 22 '11 at 22:02
  • Maybe via JSONP? The fact stands that using browser implemented XMLHttpRequests you cannot make calls cross-domain. As my response mentions: there are various ways of getting around it, eg: Ext JS's ScriptTagProxy, or JSONP (which is used by jQuery for cross-domain calls and is essentially a script tag proxy anyway). – ndtreviv Jan 05 '12 at 12:26
0

You can use a dynamic script tag to make cross domain ajax calls. As pointed here this method has some problems: It's difficult to know when the content is available, there is no standard methodology, and can be considered a "security risk".

However the method works fine in my case. refer to here for a good example. The approach is a bit tricky.

Nylon Smile
  • 8,990
  • 1
  • 25
  • 34