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?
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?
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.
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";
}
?>