Reputation: 459
I got this code from internet, it works correctly
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo $abc;?>
But when I put the </script>
at the end it stops working, kindly explain why it stops working?
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
<?php echo $abc;?>
</script>
Upvotes: 0
Views: 294
Reputation: 283
When php echos your variable $abc
, the result is approximately:
<script type="text/javascript">
var jvalue = 'this is javascript value';
<script>document.write(jvalue)</script>
</script>
Which is invalid as you can't place a script tag within another script tag (aka "nest").
Removing the <script>
tags from $abc
should fix it.
The following would work:
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "document.write(jvalue)" ?>
<?php echo $abc; ?>
</script>
I'm not a PHP expert, but I would expect that if $abc is not needed elsewhere in your code, those two PHP lines can be replaced with:
<?php echo "document.write(jvalue)"; ?>
Upvotes: 1
Reputation: 735
The syntax is not correct. According to the W3 HTML specification, a script tag cannot be inside another script tag. For future debugging purposes, try putting the entire output string through a validation check (validator.w3.org). This will inform you about coding mistakes and will help you understand the errors on which you can act.
Upvotes: 1
Reputation: 7134
The code you got will produce html like this
<script type="text/javascript">
var jvalue = 'this is javascript value';
</script>
<script>
document.write(jvalue)
</script>
But the code you changed will produce like this
<script type="text/javascript">
var jvalue = 'this is javascript value';
<script>
document.write(jvalue)
</script>
</script>
You cannot write script tag inside a script tag. That's why it producing error
Upvotes: 1
Reputation: 201497
Because abc
is <script>document.write(jvalue)</script>
and you can't nest the <script>
tag. As your second example does. You could do,
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "document.write(jvalue)"?>
<?php echo $abc;?>
</script>
You could also do,
<?php $abc = "document.write(jvalue)"?>
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php echo $abc;?>
</script>
which I think is more in keeping with the original example.
Upvotes: 2