0

I have a problem with JS and PHP:

    <?php
       $hi = "<script>document.write('hi');</script>";
       if ($hi == "hi") {
          echo("ok");
       } else {
          echo("error");
       }
    ?>

I get "error"! What is the problem?

  • 1
    i think the script is not a tag, you can call javascript in php, But i think you can't assign it as a string. I don't know much php, but if you log the $hi variable it will be string. – DILEEP THOMAS Dec 09 '18 at 15:30
  • what are you trying to achieve ? – DILEEP THOMAS Dec 09 '18 at 15:31
  • 2
    you are mixing up serverside and client side programming. – Jeff Dec 09 '18 at 15:31
  • 1
    Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Jeff Dec 09 '18 at 15:32
  • @DILEEPTHOMAS but works and print "hi"! – Amirhossein WP Dec 09 '18 at 15:40
  • @AmirhosseinWP Because echo $hi prints the javascript code, that later will be executed by the browser to print 'hi'. – Jeff Dec 09 '18 at 15:44
  • another dupe (based on the OP's comments under first answer): [Getting the screen resolution using PHP](https://stackoverflow.com/questions/1504459/getting-the-screen-resolution-using-php) – Jeff Dec 09 '18 at 15:47
  • @AmirhosseinWP you can check the post. Please let me know if it worked for you or not. – DILEEP THOMAS Dec 09 '18 at 16:29

2 Answers2

1

See the question What is the difference between client-side and server-side programming?.

PHP does not run your JS script at all -- only the browser will do that. Therefore, your $hi variable contains the entire script as a string, not the script's output. $hi = "<script>document.write('hi');</script>";.

If you want the output to be calculated before the page is sent to the browser, you would simply set $hi = "hi";, and then run your if check on it. There is no need for document.write in the server-side case.

tech4him
  • 860
  • 3
  • 20
-1

i don't know whether it can be written in a much better way, but i think this is how you can pass the variable from javascript and assign to a variable in php and you can check using an if else condition.

Note: the below code doesn't work in stack snippets. So check this link which is an online php editor Here you can add the below code and run it.

Also check whether its proper to check with a string, i think you need to convert it to a number and check. like Number("1000") => 1000 in javascript.

I hope the below snippet will solve the issue.

<script>
var p1 = screen.width;
</script>

<?php
$screenWidhFromJS = "<script>document.write(p1)</script>";
echo "Screen Width $screenWidhFromJS";
echo "<br>";
// your condition
if($screenWidhFromJS > "1000"){
 echo $screenWidhFromJS;
}else{
 echo "below 1000 screen width size";
}
?>
DILEEP THOMAS
  • 6,108
  • 3
  • 21
  • 56