A
A
Anastasia2020-05-02 02:01:38
PHP
Anastasia, 2020-05-02 02:01:38

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>

I thought it would work, but alas, no...

...
Планшеты имеют разрешение экрана, которое в разы превышает мобильное, однако на них всё равно открываются мобильные версии. Версия на смартфоне и на планшете может кардинально отличаться. На мобильнике у меня полноэкранный слайдер, а на планшете (даже в вертикальном положении) слайдер не нужен, так как всё помещается. Нет возможности разобрать слайдер. Вот такая вот вёрстка.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vorotnev, 2020-05-02
@nastya97core

In simple terms, the point is that:
- first, the PHP code (everything between <?phpand ?>) 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>

In the way you are trying you can pass data from PHP to JavaScript, e.g. <?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. Ajax
is used to send data to the server .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question