javascriptxmlhttprequestgoo.gl

Using XMLHttpRequest to shorten a url via Google's Shortener api


I've tried doing this via jQuery/ajax but it wasn't working so I thought I'd fall back to a normal XMLHttpRequest. Unfortunately, it still isn't working (same problem).

Here are the docs for Google's POST request. And here is my code:

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json");

var url = "longUrl=" + encodeURIComponent("http://www.google.com/");
console.log(url);

xmlHttp.send(url);

"url" is sent to the console as: longUrl=http%3A%2F%2Fwww.google.com%2F

The response is:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}

Does anyone see what I am doing wrong?

Thanks in advance!

Edit: Added for @Greg - so that you can see that I am following Google's spec when I'm using jQuery - which results in the SAME exact error.

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: { "longUrl": "http://www.google.com/" },
    url: "https://www.googleapis.com/urlshortener/v1/url",
    success: function(data) {
        //do something with the shortened url json data
        //console.log(data);
    }
});

Solution

  • Here is the solution (the comment from @Greg pointed me in the right direction).

    var xmlHttp = new XMLHttpRequest();
    
    xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
    xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    
    var req = new Object();
    req.longUrl = "http://www.google.com/";
    
    var jsonStr = JSON.stringify(req);
    
    xmlHttp.send(jsonStr);