1

Below is working code to use jquery+javascript with Bitly's API to shorten a link (when you have a Bitly account with a login and API key).

My question is, how can I produce the exact same result using only pure javascript with no other libraries available?

Thank you very much to anybody who can help me out.

EDIT: This question does not already have an answer (the recommended answer is not relevant at all) due to how specific this is. Also, no references to DOM are possible as this is for server-side code. Therefore every single answer in the suggested duplicate question will not work. Please do not mark this as duplicate.

I believe the way to do this is with an xmlhttprequest, but I have absolutely no idea how...

Thanks again.

var login = "LOGIN_HERE";
var api_key = "API_KEY_HERE";
var long_url = "http://www.kozlenko.info";
$.getJSON(
    "http://api.bitly.com/v3/shorten?callback=?", 
    { 
        "format": "json",
        "apiKey": api_key,
        "login": login,
        "longUrl": long_url
    },
    function(response)
    {
        alert('Shortened link is: ' + response.data.url);
    }
);
Jared Reich
  • 247
  • 4
  • 9

1 Answers1

1

Javascript libraries use the XMLHttpRequest object to make ajax calls. You could make the calls using this object. I quickly googled one up:

var xmlhttp = new XMLHttpRequest();
var url = "buildTheURLHere.com";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var jsonObj = JSON.parse(xmlhttp.responseText);
        alert('Shortened link is: ' + jsonObj.url);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

Sources:
http://www.w3schools.com/json/json_http.asp
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

But are you actually talking about node.js? You mention something about server-side code in your post. If so, http.request would be your best bet.

Nodejs:
http://nodejs.org/api/http.html#http_http_request_options_callback
How to make external HTTP requests with Node.js

Community
  • 1
  • 1
chris
  • 216
  • 1
  • 2
  • 7