user1334130
user1334130

Reputation: 1191

php to javascript int variable parsing

I am trying to parse an int value from php into a javascript variable but it is not working.

The first alert correctly displays the int value, but the second says "undefined". How can you parse the php variable correctly into the variable "test" as an integer? I tried parseInt but it didn't work. The value is for a graph so I need to at some point use the fillRect() command, the alerts are for testing only. Thanks.

    alert('<?php echo( $graph_max_max_value ); ?>');
    var test = <?php $graph_max_max_value; ?>
    alert(test);

Upvotes: 0

Views: 3034

Answers (4)

tsergium
tsergium

Reputation: 1176

You forgot an echo and you need to make sure you pass an integer value to your variable.

<script>
    <?php $graph_max_max_value = 1024;?>
    alert('<?php echo( $graph_max_max_value ); ?>');
    var test = '<?php echo $graph_max_max_value;?>';
    test.replace(/[^0-9]/g, '');
    alert(test);
</script>

Upvotes: 0

Wearybands
Wearybands

Reputation: 2455

Try this

var test = <?php echo $graph_max_max_value; ?>,

and then

alert(test);

If you dont use echo then the value is undefined

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

var test = <?php echo $graph_max_max_value; ?>; should work.

This outputs using echo, which you forgot, and adds the statement terminating semi-colon at the end.

Upvotes: 3

Quentin
Quentin

Reputation: 943163

You forgot to do anything to output the variable.

You want an echo, print, printf, etc.

(You also need to make sure that the data in PHP conforms to the syntax for a Number type in JavaScript.)

Upvotes: 2

Related Questions