0

Trying to get Screen Size from JS in PHP working

but if else conditions same value return

Please Update Questions if you understand my questions

i want to try this code not other

$screenwidth = "<script>

    var mobilewidth = console.log(screen.width); 

    if(mobilewidth < '768'){
        document.write('Mobile');
    }else{
        document.write('Template');
    }   


</script>";
echo $screenwidth;

Output = Template or Mobile in both conditions

in PHP

function LoadTemplate() {
    $screenwidth = "<script>document.write(screen.width); </script>";

if($screenwidth<=768){
    return 'Mobile';
}else{
    return 'Template';
}    
}

Output = Template or Mobile both conditions

How to fix this please help

Brijesh Patel
  • 43
  • 1
  • 8
  • PHP is executed on server side and Javascript on client side, so, PHP sends all contents to browser and only then Javascript starts its execution, they can't communicate each other with a single piece of code, you need to use another way, like AJAX or cookies, but maybe the best way is try to detect the device with PHP There are some libraries that gives you screen info. You can start here: https://stackoverflow.com/questions/4117555/simplest-way-to-detect-a-mobile-device – Triby Jan 06 '20 at 19:48
  • First you have error in your JS: `var mobilewidth = screen.width; console.log(mobilewidth);` instead `var mobilewidth = console.log(screen.width);` – Slava Rozhnev Jan 06 '20 at 19:49
  • @SlavaRozhnev Thanks it's working – Brijesh Patel Jan 06 '20 at 21:55

1 Answers1

0

console.log(screen.width) will return undefined, so you shouldn't assign it to a variable. Just do

var mobilewidth = screen.width

and if you really want to log in then follow ir with console.log(mobilewidth).

By the way, mobilewidth is a very misleading name for this variable. Call it something like currentWidth, if you need to make it a variable on its own, and use mobilewidth for the currently hard-coded 768 value.

And finally, compare to the number 768, not the string '768'.

Robin Zigmond
  • 14,041
  • 2
  • 16
  • 29
  • How to fix this `function CurrentWidth() { $CurrentWidth = ""; echo $CurrentWidth; }` **Output** call outside files Template Warning: include(/app/design/fronted/Questions/default//html/footer.php): failed to open stream – Brijesh Patel Jan 06 '20 at 23:09
  • Please create a new question, don't ask it in a comment on an answer to an unrelated one. – Robin Zigmond Jan 06 '20 at 23:43