-2

I'm wanting to set a PHP variable based on window.innerWidth.

For testing purposes, I have my browser at full size and document.write(window.innerWidth); returns 1920, which seems to be right.

However, the code below is always returning "small" for the PHP variable $window_size.

<script>
 if(window.innerWidth > 1000){
    <?php $window_size = 'big'; ?>
 } else {
    <?php $window_size = 'small'; ?>
 }
</script>

Any ideas?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
gtilflm
  • 1,389
  • 1
  • 21
  • 51

1 Answers1

-1

You can't determine the window size this way on the back end, the JS would need to send this data at some point to the back end for it to know the window size.

<script>
 var windowSize;
 if(window.innerWidth > 1000){
    windowSize = 'big';
 } else {
    windowSize = 'small';
 }
 $.ajax({ url: 'some/back/end', data: windowSize }); // send to server.
</script>

This is because PHP, your backend, generates HTML. So your Browser then gets the HTML (with JS in it) and then runs it. By that point, those PHP statements were already executed and the server doesn't know about them.

So your PHP script is executed and does the following

<?php $window_size = 'big'; ?>
<?php $window_size = 'small'; ?>

It ignores the if because it is not a PHP if statement, and so the value of $window_size is always small

SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98