0

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?

3
  • That will never work. You are defining ntime as a string and attempting to for a for loop with it. for(var i=0; i < "50"; i++) Commented Apr 10, 2014 at 20:24
  • thanks, that arr = <?php echo json_encode($czasAr); ?>; worked :) Commented Apr 10, 2014 at 20:35
  • @user3370412: I wrote a proper answer. Commented Apr 10, 2014 at 20:46

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.