Dinoo
Dinoo

Reputation: 25

How to use a php inside js

When i use the php and js separately it is working correctly

<script> var test = 'asdasdasd'; </script> <?php $id =
"<script>document.write(test)</script>"; echo $id; ?>

But when I use the php inside the js function it is not working correctly

<script>    var test = 'asdasdasd'; <?php $id =
"<script>document.write(test)</script>"; echo $id; ?> </script>

How can make work my second code?

Upvotes: 0

Views: 58

Answers (2)

Jiri Tousek
Jiri Tousek

Reputation: 12440

The second code produces wrong HTML/JS:

<script>    var test = 'asdasdasd'; <script>document.write(test)</script> </script>

- see for yourself in the generated page.

Since everything between <script> and </script> is considered to be JS code, it will try to parse the inner <script> as Javascript code...and fail.

I think the inner other of <script>...</script> tags (those that are in PHP markup) is not needed at all, just get rid of them and it will work.

Upvotes: 2

Daniels Šatcs
Daniels Šatcs

Reputation: 554

You can insert any value from php to absolutely everywhere in your file. Literally everywhere. While writing client-side code, in the right place open php tag <?php and echo what you need. Don't forget to write a closing tag ?> afterwards.

Here, you are echoing the opening script tag, which you already wrote before. That results in a syntax error:

<script>
<script>
...
</script>

Upvotes: 1

Related Questions