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?

2
  • 1
    Possible duplicate of how to write javascript code inside php Commented Aug 20, 2016 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, <?php echo "<script> your code here </script>"; ?> Commented Aug 20, 2016 at 22:34

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

closing the PHP tag and reopen it will be easy for long codes
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. :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.