How do I get a value from a JavaScript code and use it in PHP?

-1

I need that when the width of the browser is between some stipulated values, my variable $colunas assumes 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 gets a value of 2, regardless of whether I change the width of the browser.

    
asked by anonymous 03.11.2015 / 14:01

2 answers

3

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 locations. One is not a continuation of the other.

If you want to do this, you have to get the information in JS within the existing page and send it to PHP for some use. But in fact this is not the ideal and does not seem to want to do this. 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 the content, it should not be responsible for the presentation format of the page.

You have information about this here. But if you have any specific questions, open a question about this.

    
03.11.2015 / 14:06
0

The problem is that PHP runs on the server, before the javascript that runs in your browser (or that of the client), so the value of $ width will always be the same.

Look for link and link

    
03.11.2015 / 14:11