How to take a value from a Javascript code and use it in PHP?

Asked

Viewed 110 times

0

I want that when the width of the browser is between some values stipulated, my variable $colunas assume different values.

I have the following code:

<?php
$largura = "<script type =text/javascript>var largura =  document.body.clientWidth; document.write(largura); </script>";
echo $largura, '<br>';
$colunas = 0;
if ($largura > 1800) {
    $colunas = 4;
}
else if (($largura >= 1450) and ($largura <= 1800)) {
    $colunas = 3;
}
else if($largura <= 1449){
    $colunas = 2;
}
echo $colunas;

But my variable $colunas always receives the value equal to 2, independent of I change the width of the browser.

  • Browser width? I believe this should be done with javascript, otherwise you will have to load any changes.

2 answers

5


This does not exist, you are mixing PHP with Javascript. They are different languages and run completely separately. Not only at different times, but in different places. One is not a continuation of the other.

If you want to do this, you have to get the information in the JS inside the existing page and send it to PHP to use in some way. But actually this is not ideal and it doesn’t seem like you want to do it. In fact this is an old way of solving this problem.

The solution is to solve everything on the client side, with CSS and eventually JS. PHP should only generate content, not be responsible for the presentation format of the page.

You have information about this here on the site, but if you have any specific questions, ask a question about this.

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.