When adding a variable that I passed from JS to PHP it adds [closed]

-5

I can pass the variable from JS to PHP, but when I try to add it it simply disappears.

<!DOCTYPE html>
<html>
<head>
    <script>
        var width = screen.width;
        var height = screen.height;
    </script>
</head>

    <?php $width = '<script>document.write(width);</script>';
    $php = $width + 10;

    echo $php;
    ?>
</body>

    
asked by anonymous 12.01.2017 / 17:26

2 answers

13

PHP is back-end and JavaScript is front-end.

What PHP does is generate a page, it can be html, txt, image, etc, ie it runs on the server before reaching your browser, JavasSript already runs on browser .

Read these answers, although the focus is other things, I explain how the request and response interaction works, I recommend you read:

What the server does is send only the response of what PHP has generated for your browser, PHP has already been run and terminated, so you do not have JavaScript to communicate with PHP unless it is by Ajax ( which is a background request).

When you do this:

$width = '<script>document.write(width);</script>';

You are not passing the value from width to $width , actually PHP is seeing <script>document.write(width);</script> and not width .

You do not know how PHP knows the value of the screen size in the same request, what you can do is use Ajax, for example:

On your page add this to your page:

<script>
(function ()
{
    function enviarTamanhoTela()
    {
        var querystring  = "largura=" + screen.width;
            querystring += "&altura=" + screen.height;

        var oReq = new XMLHttpRequest();

        //envia querystring como se fosse uma página normal
        oReq.open("GET", "atualizatamanho.php?" + querystring, true);

        //Função assíncrona que aguarda a resposta
        oReq.onreadystatechange = function()
        {
            if (oReq.readyState === 4) {
                alert(oReq.responseText); //Pega resposta do servidor
            }
        };

        //Envia a requisição, mas a resposta fica sendo aguardada em Background
        oReq.send(null);
    }

    if (/^(interactive|complete)$/i.test(document.readyState)) {
        enviarTamanhoTela();
    } else {
        document.addEventListener('DOMContentLoaded', enviarTamanhoTela);
    }
})();
</script>

And create a new file called atualizatamanho.php , you can get the data like this:

<?php

if (isset($_GET['largura'], $_GET['altura'])) {
    $largura = $_GET['largura'];
    $altura = $_GET['altura'];

    var_dump($largura, $altura); //Pode remover essa linha

    //Resto do seu código aqui
}
    
12.01.2017 / 17:37
-6

You're trying to add a string with an integer.

try to convert the $width variable. ex.

$width = (int) 10.9;

var_dump( $width );
    
12.01.2017 / 17:34