Answer the question
In order to leave comments, you need to log in
How to transfer from js to php inside the template?
Hello. in php I connect the home.tpl file via include. Inside this file, I need to do something like this.
<script>
if (screen.width>500) {
<?php $type = 2; ?>
} else {
<?php $type = 1; ?>
}
</script>
Answer the question
In order to leave comments, you need to log in
In simple terms, the point is that:
- first, the PHP code (everything between <?php
and ?>
) will be executed on the server, and in your case it will be empty, because the $type variable will only exist on the server at the time this code fragment is executed, this the code in this place does not output anything (does not echo, print, printf, etc.).
- next, an HTML page will be generated that contains JavaScript code (everything between <script>
and </script>
), but once again - there will be no PHP code there (it has been executed), instead it will be the result of this execution (in your case it is empty, see above )
- JavaScript code is executed by the browser after it is generated on the server and downloaded from there by this same browser. And in the browser, your script, given that PHP did not print anything there, will look like this:
<script>
if (screen.width>500) {
} else {
}
</script>
<?php echo $type; ?>
print the value of the $type variable in JS. You won’t transfer data back from JS to PHP, it’s like traveling back in time to 1994. AjaxDidn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question