3

I want to know the size (in kbyte / byte) of the response to an ajax call (.get, .post, .ajax) - any ideas?

Thanks!

Roman
  • 4,443
  • 14
  • 56
  • 81

3 Answers3

2

Just check data.length. Here is an example:

$.get('ajax/test.html', function(data) {
  alert(data.length);
});
jonjbar
  • 3,896
  • 1
  • 25
  • 46
  • Won't that just give you the character count? No information on headers size and such... – peirix Oct 17 '11 at 09:43
  • I agree - that would give you only the char length. Though, you could say that each char is 8 byte long, no? – Roman Oct 17 '11 at 09:44
  • Indeed, this is the length of the data in number of characters, or Bytes. You can convert it to Bits by multiplying by 8 if needed. – jonjbar Oct 17 '11 at 10:02
  • 1
    It's not the same when you are dealing with compressed data. – Mark Biesheuvel Sep 08 '12 at 21:28
  • Rather then using data.length to get the length of response, I would suggest you to follow https://stackoverflow.com/a/58392250/6879925 after that you can convert it into byte,KB,MB... so on as per your requirement – Dinesh Gopal Chand Oct 15 '19 at 10:17
2

I figure you 's best check this size in the debugger tools of your browser. You can get the data length, as suggested by John Riche, but this is only the character length. The actual byte size of this data alone may vary, depending on the used encoding. And then you got your headers too.

Unfortunately I think you cannot read this information from Javascript itself.

If you use Chrome, press F12 to open the development tools, and choose 'Network', you get an overview of requests, including AJAX requests. For each request there's a byte size of both the response content and the entire response. In FireBug you should be able to see similar data.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • Checked with firebug - works great! though not automatic enough, it's the best idea so far :) Many thanks! – Roman Oct 17 '11 at 09:49
0

you can get the "Content-Length" of the response header:

    var contentsize;
$.ajax('url',function(data,textstatus,request){
         contentsize = request.getResponseHeader("Content-Length")/1024;
         //do stuff with your data
        });
Entrabiter
  • 752
  • 7
  • 13
  • 1
    Content-Length was not available in Chrome but anyone finding this in the future should check: jqXHR.responseText.length It is the response in string form. Getting the length will give you the total bytes. – Robert Brisita Oct 05 '13 at 00:39