1

Using https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js I have the following to try and POST a JSON request to Google's URL Shortener

$.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: "https://www.googleapis.com/urlshortener/v1/url",
  data: { longUrl: "http://some.url" }
})
  .done(function( msg ) {
    console.log( msg );
  });

This comes back as a 400 error because the request isn't formatted correctly. Looking at the request in fiddler, I can see it's like this;

POST https://www.googleapis.com/urlshortener/v1/url HTTP/1.1
Host: www.googleapis.com
Connection: keep-alive
Content-Length: 29
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/javascript, */*; q=0.01
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/json
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,fr;q=0.4

longUrl=http%3A%2F%2Fsome.url

I can modify the request to the following, which works (excluding header);

{ longUrl=http://some.url }

So why is ajax not formatting the data as a JSON?

JPain
  • 305
  • 1
  • 9

3 Answers3

3

jQuery doesn't turn objects into JSON strings for you. dataType is for the response, and contentType is for the server's benefit. You still have to actually serialize the data to JSON:

$.ajax({
/* ... */
  data: JSON.stringify({ longUrl: "http://some.url" })
})
CupawnTae
  • 14,192
  • 3
  • 29
  • 60
1

Did you try: JSON.stringify ?

Something like this:

data: JSON.stringify({ longUrl: "http://some.url" })
Bhaskara
  • 601
  • 9
  • 18
0

If you pass your json object as a string, your request will return ok for instance I got an object back with this url http://goo.gl/UXeQ.

See http://jsfiddle.net/3oy3c5tq/

$.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: "https://www.googleapis.com/urlshortener/v1/url",
  data: '{ longUrl: "http://some.url" }'
})
  .done(function( msg ) {
    console.log( msg );
  });
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
  • 1
    Strictly speaking for it to be valid JSON you'd need to quote the `longUrl` as well.. `'{ "longUrl": "http://some.url" }'` - obviously google doesn't mind so much – CupawnTae Dec 08 '14 at 18:12