Formula-G
Formula-G

Reputation: 29

How can I use the javaScript value in php

I have a question about using javaScript value in PHP:

var i; <br>
for(i=0;i<4;i++){ <br>
    alert("echo $MarkA[i]");<br>
}

$MarkA is a PHP array
I want to know that how can I using the javascript value 'i' in PHP code.
Thanks.

Upvotes: 1

Views: 116

Answers (2)

Ram
Ram

Reputation: 144689

That's not how PHP works. You can't mix client and server-side scripts that way. One option is creating a JavaScript variable:

<script>
   var marks = <?php echo json_encode($MarkA);?>;
   for(i=0;i<4;i++) alert(marks[i]);
</script>

Upvotes: 4

Naga
Naga

Reputation: 2168

You cannot use client side script variable into server side script. But you can parse the PHP array using the below method. No need javascript increment variable.

<?php $MarkA = array(1,2,3,4);?>

<script>
var json = JSON.parse("<?php echo json_encode($MarkA);?>");

$.each(json,function (i,item) {
    console.log(item);
});
</script>

Upvotes: 0

Related Questions