0

I'm trying to get the browser's width and then compare it as a php variable, but it is saving it as a string, I tried parsing it to another variable but it only returns 0.

$tam='<script>var j= $(window).width(); document.write(j)</script>';

I'm doing the parsing like this:

$ntam=(int) $tam;
  • 3
    Are you aware that the PHP code is executed on the server, and the Javascript is executed on the client (browser)? Here, $tam in PHP will always be a string. Nothing more, nothing less. – laruiss Oct 01 '14 at 17:58
  • so there is no way to parse the variable? – Kevin Garduño Oct 01 '14 at 18:06

2 Answers2

0

You can't save a javascript value into a php variable directly. But you can....Put the php value into a javascript variable and use that for making your changes using javascript.

<?php  echo '<script type="text/javascript">var jVar = "$phpVar";'; ?>

If you are importing your script from a js file you will want to add this before your import or course.

And I'm not sure what you're trying to accomplish but if you need a js value you can always send that value using an ajax Request...

var ajax = new XMLHttpRequest();
var form  = new FormData();
form.append('win_size',window.innerWidth);
ajax.open("http://example.com/processJSWindowSize.php","POST",true);
ajax.send(form);

On the server side code, which in this example is processJSWindowSize.php, you can have something along the lines of

<?php 
    if($_SERVER['REQUEST_METHOD'] == 'POST'){ 
        $jsWindowSize = strip_tags(stripslashes($_POST['win_size']));
        //do what you need with the window size

    } 
?>
ksealey
  • 1,698
  • 1
  • 17
  • 16
-1

Your script needs to return the width and it needs to be a function

      <script>
        var tam= function()
            {
              var j= $(window).width(); 
              document.write(j)
              return $(window).width();
            }
       var ntam = tam;
      </script>
DJ Burb
  • 2,346
  • 2
  • 29
  • 38