views:

530

answers:

3

Hey,

I am having a peculiar problem with getting an integer from an ajax response. Whenever I call the following code, parseInt(data) returns NaN despite data being a string.

function poll() {
    $.ajax({
      type: "GET",
      dataType: "html",
      url: 'images/normal/' + userId + '/' + saveCode + 'progress.txt',
      error: function() {poll();},
      success: function(data) {
        // Change the text
        $('#loading_text').html(data + '% complete');
        // Change the loading bar
        max = 357;
        current_percent = parseInt(data); // returns NaN
        $('loading_bar').width(Math.round(max * (current_percent / 100)));
        // Call the poll again in 2 seconds
        if (loaded != true)
            {
            setTimeout( poll, 2000);
            }
      }
    });
}

In firebug, typeof(data) is string and data = "89" (or another number from 1-100) yet it still isn't working. Any clues?

A: 

Try browsing every character of the string programmatically, perhaps there's an unprintable character that's preventing the parseInt to execute.

Paulo Santos
An easy way to do this is to print out encodeURIComponent(data) -- it should show any unprintable characters url-encoded.
Annie
+2  A: 

Are you sure the data is exactly "89"? If the first non-whitespace character in the string can't be converted to a number, parseInt() returns NaN.

Also, it's a good practice to specify the radix with parseInt, to force the conversion that you're looking for. Try parseInt(data, 10).

womp
+1 for comment re: supplying the base 10 radix
Funka
I tried parseInt(data, 10) however there was no difference. As for whitespace, I looked through all the characters and couldn't find anything weird. I passed it through the trim function found at webtoolkit.info/javascript-trim.html and that didn't help. This is getting quite frustrating
Lobe
+1  A: 
data="89"
typeof(data) //is string
typeof(+data) //is number

So you can also give it a try with Plus + sign, instead of using parseInt

A different with + sign and parseInt as far as I know is when you parse blank or whitespace strings, parseInt return NaN, and + returns 0

S.Mark
typeof(+data) returns number, however just +data on its own returns NaN
Lobe
Can you do alert(data.length)? I think you have some non-numbers before "89".
S.Mark
That makes a lot more sense now. data.length = 211. That's probably caused by my php code which updates the text file 105 times to provide progress updates, so it's not cleaning up the file correctly. Whats's the best way to fix this up? I thought the trim functions would have worked
Lobe
Hi Lobe, I think we need to know some codes and info like how you updating that texts files, and what kind of logic behind, etc. I think you can ask as new question for that particular issue, I am not so good with php also.
S.Mark