Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaScript variable in PHP?

I am trying this code:

<script type="text/javascript">
for (i = 0; i < 5; i++) {
    for (x = 0; x < 1; x++) {
        $("#one" + i).html("<?php echo $arr["+i+"]["+x+"] ?>");
        $("#two" + i).html("<?php echo $arr["+i+"]["+x+1+"] ?>");
    };
};

</script>

No error is showed, but content also not.

How can I use the increment variable of JavaScript in PHP code?

Thanks

like image 909
Daniel Avatar asked Dec 04 '25 19:12

Daniel


2 Answers

You may make your PHP-array accessible to JS(store it as a js-variable) :

<script type="text/javascript">
var arr=<?php echo json_encode($arr); ?>;
for (i = 0; i < arr.length; i++) {
    for (x = 0; x < 1; x++) {
        $("#one" + i).html(arr[i][x]);
        $("#two" + i).html(arr[i][x+1]);
    };
};
</script>
like image 101
Dr.Molle Avatar answered Dec 06 '25 08:12

Dr.Molle


You cannot do this.

Javascript runs on the client, which is after all PHP code has executed.

Why don't you write the loop in PHP instead? For example,

<script type="text/javascript">
<?php
for ($i = 0; $i < 5; $i++) {
    for ($x = 0; $x < 1; $x++) {
        printf('$("#one%s").html("%s");', $i, $arr[$i][$x]);
        printf('$("#two%s").html("%s");', $i, $arr[$i][$x + 1]);
    };
};
?>
</script>
like image 43
Jon Avatar answered Dec 06 '25 09:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!