4

I did an AJAX call which just returns a number:

var lastID = 0;
var loading = true;

// Get latest message ID
$.ajax({
    url: "libs/getLatestMessageID.ajax.php",
    dataType: "text",
    type: "GET",
    success: function(data) {
        lastID = data;
        console.log("Received latest message ID: " + typeof(data) + " \"" + data + "\" " + parseInt(data, 10));
    },
});

What I receive from the server is a string, e.g. "21", which now needs to be converted to a number so JS can calculate with it. In Firefox, it works fine, the output of the console.log() row is:

Received latest message ID: string "21" 21

But Google Chrome makes parseInt() return this:

Received latest message ID: string "21" NaN

What goes wrong here?

3 Answers3

5

The string is prefixed with non-printable invalid chars which causes the parseInt() to not be able to parse the string as number and therefor returns NaN (Not-a-Number).

As in comment you can check this by escaping the string:

... + escape(data) + ...

You can also use data.length to see if the string is of the length you expect.

You need to find the source for this (probably encoding related) so you can prevent the string for being prefixed this way. If you are unable to find the source a temporary solution would be to strip the string before you pass it to parseInt() but this is not recommended for a final solution.

You can use for example a regEx to strip of the non-numeric chars:
Regex using javascript to return just numbers

(or use something as suggested in the comments)

But in the end you will want to find the source.

Update thanks to @fero's link it indicates that the char you are getting comes from a BOM marker in your original file to indicate byte-order.

You could re-write your file without this marker or try to strip it off at server side before sending the data. If your data is UTF-8 this won't have an effect on the data itself.

Community
  • 1
  • 1
  • 1
    This is a good answer. Let's see wheter I can find the problem. Mabye it encoding related? The AJAX ouput comes from an UTF-8 file... – webdesigner97 Jan 29 '14 at 07:54
  • @webdesigner97 it can be encoding related. You could check what encoding your page is using (or set an explicit encoding to what you use UTF-8) and also check if your server is configured to return the data in the same encoding. –  Jan 29 '14 at 07:55
1

Try this:

console.log("Received latest message ID: " + typeof(data) + " \"" + data + "\" " + parseInt(data.match(/\d/g).join("")));

Actually I am filtering the numbers from data with regex as I think there is some non-numeric data is coming.

Ashish Kumar
  • 2,991
  • 3
  • 18
  • 27
0
var data = parseInt(" 21", 10);
alert(data);

It works for me in Google chrome 32.0 and firefox 27

Kaptan
  • 336
  • 2
  • 11