0

I need screen size of visitors. so i use this javascript.

<script>
var screenWidth = window.screen.width,
    screenHeight = window.screen.height;
 
 alert (screenWidth);
 
</script>
<?php
   $value = $_POST['val'];
   echo "I got your value! $value";
?>

now, i need to pass this value in php code, without refreshing page and i also don't want to click on submit button

Deep Kakkar
  • 4,538
  • 4
  • 26
  • 58

1 Answers1

2

High level: Browser sends request to server, then the server responds with something (in this case dynamically generated html), browser then parses this html and makes and DOM. You can then script against the DOM at this point with javascript.

Usually by the time you're in the browser scripting in javascript, you can't just pass a value to PHP without making a new request.

At least two options to make that request:

  1. If you just want to send data to the server without a page refresh, you're looking for AJAX. Then you'll have to do something with that response like dump it into the DOM. You'd have to do this on every page reload.

  2. Another option in your case: since you probably want to serve different html based on the users screen since on multiple requests you can set a cookie with javascript. Then every subsequent request will contain that cookie which you can read with PHP. Good write up on this technique here: https://css-tricks.com/server-side-mustard-cut/

Nathanael Smith
  • 2,543
  • 1
  • 11
  • 11