2

I am wanting to display slightly different content/layout for mobiles so I am setting a flag using PHP/Javascript:

<script type="text/javascript">

  if (screen.width <= 700) 
  {
  "<?php $mob=1; ?>";
  }

</script>

But this doesn't seem to work, is the syntax correct?

Thanks.

davidjwest
  • 520
  • 2
  • 20
  • 2
    http://mobiledetect.net/ – Rayon Apr 07 '16 at 08:28
  • This task which sounds simple at first is in fact very complicated to achieve. You definitely cannot do what you are doing because JavaScript is executed client side and cannot set PHP variables which has already been executed on the server side. Also, a smaller screen width may indicate lower resolution or someone just not having their browser maximized. – apokryfos Apr 07 '16 at 08:29
  • Related: http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – T.J. Crowder Apr 07 '16 at 08:39

1 Answers1

2

You need to undrestand the difference between what happens on the client and what happens on the server.

Your JavaScript code is running on the client. By that time, your PHP code has already finished running, producing the output that is sent to the browser.

E.g., here's what happens:

  1. Browser sends request to server
  2. Server runs your PHP code to produce the response
  3. Response is sent to browser
  4. Browser renders response and runs any JavaScript it contains

So your JavaScript code cannot directly set a PHP variable.

More on client-vs-server in this question and its answers.

If you need to know the screen resolution in your PHP code, this question and its answers tell you why you can't do that and what to do instead.

But ideally, have your PHP provide the content, then use CSS media queries to choose how to format it (including whether to hide some of it) on smaller page sizes:

@media screen and (max-width: 700px) {
    /* These rules only apply when display (vs. printing, etc.)
       on a page with a width of 700px or less
    */
}

One advantage to that is that it's dynamic: If the user reorients their mobile device into landscape mode and it's now more than 700px wide, your content is displayed in the larger format without re-requesting it from the server. similarly, on a desktop, if someone starts out with a window 1000px wide but then narrows it to 600px, your content adjusts, again without a re-request to the server. (You probably know, but this is called "responsive design.")

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639