0

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?

GeekWithGlasses
  • 572
  • 2
  • 12
  • 30
  • 1
    Possible duplicate of [how to write javascript code inside php](http://stackoverflow.com/questions/10596218/how-to-write-javascript-code-inside-php) – muya.dev Aug 20 '16 at 22:21
  • 2
    You need to `echo` the whole JS inside the `php` tag because PHP doesn't know anything of what you're doing with it. Like, ` your code here "; ?>` – Raktim Biswas Aug 20 '16 at 22:34

3 Answers3

1

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
Diogo Eichert
  • 437
  • 6
  • 17
0

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.

GeekWithGlasses
  • 572
  • 2
  • 12
  • 30
0

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. :-)

francis94c
  • 74
  • 1
  • 6