I am trying to write a javascript inside php tags my javascpript is here
<script>
$('#img').attr("src","getImage.php?id="+);
$('#img').show();
</script>
and what I am doing is here
<?php
echo "<script>";
echo " $('#img').attr(\"src\",\"getImage.php?id=\"+1); ";
echo " $('#img').show(); ";
echo "</script>";
?>
what is wrong here?
3 Answers 3
Your script tag is just like any other HTML tag, just close your PHP tag before opening it:
?>
<script>
$('#img').attr("src", "getImage.php?id=" + 1);
$('#img').show();
</script>
<?php
Comments
what I was doing wrong is , I was echoing the js in parts. What I needed to was something like this
<?php
echo " <script>
$('#img').attr(\"src\",\"getImage.php?id=\"+2);
$('#img').show();
</script> ";
?>
whole js in just 1 peice is the key here.
1 Comment
I'm guessing the reason you are echoing javascript via php is that u want to be able to generate dynamically the number you add to the end of the image source/src tag. you can do it as follows...
As far as your php file is saved with extension of '.php' you can do this without errors:
<?php $n = 2; //Declaration of n ?>
<script>
$("#img").attr("src", <?php echo "\"getImage.php?id=$n\"" ?>);
$("#img").show();
</script>
And that is it, just use the php open and closing tag where u need to output something dynamic... other than that, leave pure javascript out side to avoid confusion. Make sure u provided a link to jquery library as well as i can see that from your syntax u intend to use jquery. hope this helps. :-)
echothe whole JS inside thephptag because PHP doesn't know anything of what you're doing with it. Like,<?php echo "<script> your code here </script>"; ?>