Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the length of jQquery Ajax Response

I need to count the length of an Ajax response done in jQuery. The response is in JSON format and only contains a single string. I get the value but have no idea how to count the length of this string.

Here's my code :

var tempId;
$.ajax({
    url: "<?=base_url();?>index.php/sell/decoder",
    type: "POST",
    data: {'str' : sometext},
    dataType: 'json',
    async: false,
    success: function(response) {
        tempId = response; // This gives me a return value as a string. For example = 153
        alert(tempId.length); // But this returns "undefined". What should I do to get the length?
    }
});

Here's the structure of the response header:

Connection  Keep-Alive 
Content-Length  2
Content-Type    text/html
Date    Fri, 06 Jul 2012 08:12:12 GMT
Keep-Alive  timeout=5, max=86
Server  Apache
X-Powered-By    PHP/5.3.10
like image 899
under5hell Avatar asked Jul 06 '12 07:07

under5hell


2 Answers

Do an if condition then convert it to string first, then count the length as needed.

success: function(response) {
    if(response){       
      alert( (response + '').length );
    }
}
like image 51
fedmich Avatar answered Oct 19 '22 19:10

fedmich


Or convert your value (I guess it is an integer) to string:

tempId.toString().length
like image 31
Niranda Avatar answered Oct 19 '22 20:10

Niranda