andrewtweber
andrewtweber

Reputation: 25569

Issue with jQuery data() treating string as number

I have a MySQL BIGINT that I am storing in HTML5 data. Then I'm trying to access that value and pass it through an AJAX call.

<div data-id="211285677671858177">

And the JavaScript:

var send_data = {
    id: '' + $(this).data('id')
}
$.post('/send.php', send_data);

The issue is that the jQuery data function seems to retrieve that value as a floating point and not a string. So appending it to a blank string isn't helping because it's already too late - it's already been rounded (in this case to 211285677671858180). What can I do to fix this?

Upvotes: 52

Views: 19005

Answers (5)

John Flatness
John Flatness

Reputation: 33789

This isn't a case of "long int" really, the number you're getting is the closest available representation as a floating-point number.

Anyway, you want the value as a string. Quote the jQuery docs for .data (emphasis mine):

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

Upvotes: 80

Abhishek Shrivastava
Abhishek Shrivastava

Reputation: 749

I had a similar issue where the data id (alphanumeric) was getting converted through usage of .data() as a result the last few characters were getting converted to all zeroes. It took some research to determine that this is a bug in jQuery implementation of .data().

Reference: http://bugs.jquery.com/ticket/7579

For me, to get the data id directly as a work around, I used .attr("data-id") directly and this gave me the correct id.

Upvotes: 0

moribvndvs
moribvndvs

Reputation: 42497

Try surrounding the data attribute value in single quotes, if you want data to treat it like a string. Problem there, I guess, is you'll have the quotes to strip.

Upvotes: 0

Pointy
Pointy

Reputation: 413836

There's no such thing as a "long integer" in JavaScript. All numbers are 64-bit floating point. Your number there cannot be represented exactly in IEEE-794 floating point representation.

The only way to "fix" this is to make the number into a string in a domain that can cope with big integer values.

Upvotes: 3

user967451
user967451

Reputation:

try typecasting it to string:

id: '' + $(this).data('id').toString();

Upvotes: 2

Related Questions