user4488719
user4488719

Reputation:

Why is Javascript event handler changing my PHP variable?

I have a webpage(page1.php) form that posts to another PHP page(page2.php) with an access login form. I am trying to auto insert 2 of the $_POST variables into the access login form. The process on page2.php is as follows:

// assign the $_POST variables.
$number = $_POST['number'];
$accessCode = $_POST['accessCode'];

// quick check of the data type of $number
printf('Number: ' . $number . ' - ' . gettype($number) . ' data type <br />');

// The access login form...
printf('<form>');
printf('Number <input name="practiceNumber" id="practiceNumber" /><br />');
printf('Access Code <input name="practiceCode" id="practiceCode" />');
printf('</form><br /><br />');

//outside the </php ?> tags, the JavaScript to auto insert the values after 3 secs...
<script type="text/javascript">
var myVar=setInterval(function () {myTimer()}, 3000);
function myTimer() {
document.getElementById("practiceNumber").value = <?php echo $number); ?>;
document.getElementById("practiceCode").value = <?php echo $accessCode; ?>;
}
</script>

</php
// quick check to see if the data type of $number has changed
printf('Number: ' . $number . ' - ' . gettype($number) . ' data type <br />');

The browser output inserts the values into the form fields, but changes the string $number '5021251000801111111' to '5021251000801111000'.

Why is the string $number '5021251000801111111' changed too '5021251000801111000' when using JavaScript to insert the value?

Upvotes: 1

Views: 62

Answers (2)

Felix D.
Felix D.

Reputation: 2220

Numbers in ECMAScript are internally represented double-precision floating-point. When value is set to 5021251000801111111 (0x45AF112E76D32C47 in hex), it is assigned the nearest representable double-precision value, which is 5021251000801111000 (0x45AF112E76D32BD8).

You can use that library or any similar project if you want to manipulate large numbers without resorting to strings.

https://github.com/jtobey/javascript-bignum

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816532

5021251000801111111 is larger than the greatest integer that JS can represent precisely. Because that lost precision, you get 5021251000801111000 instead.

> Number.MAX_SAFE_INTEGER
9007199254740991

Use a string instead.

Upvotes: 2

Related Questions