0

I've an object like

{
    "Id": 1,
    "Value": 10,
    "UId" : "ab400"
}

How can I calculate the length of this so that I'm able to send it in ajax request.

 $.ajax({
    url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
    type:"POST",
    data: data,
    headers: {
        "Content-Type":"application/atom+xml",
        "Content-Length": data.length,

I tried using stringfying the JSON but the length comes incorrect Tried : JSON.stringify(data).length

Ecko123
  • 308
  • 1
  • 4
  • 16
  • what do you mean, incorrect? – vaso123 Dec 01 '14 at 11:40
  • 1
    what do you mean by "length" of an object? the amount of key/value pairs? please be more precise. JSON.stringify(data).length will give you the amount of characters in you object string – Max Bumaye Dec 01 '14 at 11:40
  • 1
    Why are you putting `JSON.stringify` anywhere near `application/atom+xml`?! – Quentin Dec 01 '14 at 11:41
  • This might help you: http://stackoverflow.com/questions/17762778/how-to-calculate-content-length-in-javascript – M. Page Dec 01 '14 at 11:47
  • 1
    If you look in the Network Inspector you will see the content length header is added automatically. – Alex K. Dec 01 '14 at 11:49
  • 1
    What you're doing makes no sense; jQuery sends the object using `application/x-www-form-urlencoded`, you're determining the length using the JSON representation and the headers say you're sending XML ... very confusing. – Ja͢ck Dec 01 '14 at 11:55

2 Answers2

0

You are calculating the length correctly, so possibly a syntax error before the ajax request.

var data = {
    "Id": 1,
    "Value": 10,
    "UId" : "ab400"
}

var dataLength = JSON.stringify(data).length;

$.ajax({
  url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
  type:"POST",
  data: data,
  headers: {
    "Content-Type":"application/json; charset=utf-8",
    "Content-Length": dataLength
  },
  success: function(data){
    console.log(data);
  },
  error: function(data) {
    console.log(data);
  }
});
svnm
  • 22,878
  • 21
  • 90
  • 105
0

you should use JSON.stringify() to get the complete string then apply length attribute to get length.

    var data = {
            "Id": 1,
            "Value": 10,
            "UId" : "ab400"
        }

        var Length = JSON.stringify(data).length;
         console.log(Length);//33
         console.log(data.length);//undefined, because here data is object not string. 
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
  • Will never give you correct length of the data..You can try it yourself..Stringify adds additional / in order to make object as string – Ecko123 Dec 02 '14 at 07:19
  • no just log this and count each char : console.log(JSON.stringify(data));// here no / will be there – Suchit kumar Dec 02 '14 at 08:12