Get php variable in javascript

I had an interesting problem. I am currently developing a php page and you need to access the php variable in javascript onload.

$(document).ready(function() { var temp = <?php $page_id ?> } 

Is this really so? I know this may seem strange and not allowed, but I am developing a page with two pop-ups. Windows are created using the same presentation template, and there is no way to distinguish each other. If I saved a hidden value on a page with information unique to that page, so

 <input type="hidden" value="<?php $page_id ?> id="page_id" /> 

if two views open simultaneously, for me there is no way to get a unique page identifier

 var temp = $("#page_id").val(); 

Because there are two views with the same input identifier, which is not unique. In short, is it proper to refer to a php variable in javascript?

+4
source share
6 answers

In short, this is true for referencing a php variable in JavaScript.

The short answer is yes, you can ... PHP is a server language, you can use it wherever you want.

Note: I assume that you are doing this in a file with the php extension.

+1
source

In short, is it proper to refer to a php variable in JavaScript?

You are not referencing a PHP variable in JavaScript. You simply generate JavaScript code dynamically through PHP, where the value of the PHP variable $page_id becomes hard-coded into JavaScript code.

If you build your JavaScript code via PHP, and use var temp = <?php echo $page_id ?> , It will work, but I would not consider it the best practice for large projects. I prefer my JavaScript code to remain static.

+1
source

You will find your answer in this question .

0
source

Your first piece of code is valid as long as you create javascript. The same does not work if you put your js code in a separate .js file. Generating dynamic js is not good practice for several reasons, such as caching and reusing js browser.

If you want to completely separate php js code, you can create a client-server connection where js will request a specific value from php script via ajax and later play with it in js environment.

0
source

The only thing you need is some clarification.
In essence, you cannot pass a variable. You can only pass its value.
In addition, you cannot "pass" anything from PHP to javascript. Javascript is generated by PHP. This is similar to HTML. You just generate whatever code you want. And you can use any variables, of course, with this code generation.

0
source

The second example will work too, but you need to repeat the value of the PHP variable on the page so that JavaScript can read it. Also use htmlspecialchars to make sure you are not done with invalid html.

 <input type="hidden" value="<?php echo htmlspecialchars($page_id, ENT_QUOTES) ?>" id="page_id" /> 
0
source

Source: https://habr.com/ru/post/1309097/


All Articles