Im trying to move Js variable into php , simply put var i instead of const 4
var ntime = '<?php echo count($czasAr);?>';
for (var i = 0; i < ntime; i++) {
alert('<?php echo $czasAr["4"];?>');
};
I have tried
<script>document.write(i)</script>
but it didn't work, alert was empty. any ideas?
You can't move a client-side language variable to a server-side language like PHP directly for security reasons. That would be the end of the internet as we know it.
What you can do is for example do a GET request to the same page that contains a PHP script which will get the variable from the request. For example
JS part:
var yourVariable = "lorem";
document.location = "/theSamePage.php?variable=" + yourVariable;
PHP part:
$passedVariable = $_GET['variable'];
echo $passedVariable;
Or you can do a form for example which will handle this.
You cannot iterate over a PHP array in JS. You might be better off injecting the whole array into JS and then iterate over it:
var arr = <?php echo json_encode($czasAr); ?>;
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
The PHP and JS code usually run on different computers, you cannot simply mix those languages. PHP is executed on the server side, generating HTML and JS code, and JS is executed on the client in the browser. Read up on the client-server model.