Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting TinyUrl in Javascript

Tags:

javascript

function ShortUrl(bigurl)
{
$.getJSON(
  "http://tinyurl.com/api-create.php",
   url: 'http://dfsghdsvfbjvjd.com',
  function(data){
   alert(data);
  });
}

Not Working

$['getJSON']('http://tinyurl.com/api-create.php?url=http://xxxxxxx.com/', function (a) {
                         h = a;
alert (h);

                     });

This Call is Also Not Working. Tried Various calls but not getting tinyurl.

like image 918
Johan Avatar asked Mar 24 '23 08:03

Johan


2 Answers

The API you are using is not returning the shortened URL as JSON but as plain text. And there is no way to extract plain text data from another domain (here tinyurl) with an AJAX call. See same origin policy.

If all you want to do is shorten an URL client-side, bit.ly has an API that supports JSONP.

$.getJSON('http://api.bitly.com/v3/shorten?callback=?',
    {
        format: "json",
        apiKey: YOUR_API_KEY,
        login: YOUR_LOGIN,
        longUrl: "http://link.to.be/shortened"
    },
    function(response) {
        console.log(response.data.url);
    }
);
like image 164
thibauts Avatar answered Apr 06 '23 02:04

thibauts


You don't need $.getJSON with this api link like: http://tinyurl.com/api-create.php?url=google.com. Because it returns the short url as plain text.

So, I think this would be enough:

$.get("http://tinyurl.com/api-create.php?url=google.com", function(shorturl){
    alert(shorturl)
});

See: http://api.jquery.com/jQuery.get/

like image 32
K-Gun Avatar answered Apr 06 '23 01:04

K-Gun