2

this is the path i'm using in an img src attribute which i'm using in a php program

'user/hangout_images/".$imag_addr." '

can anybody tell how to insert the path given above into the path given in the following javascript code?

$(document).ready(function() {
  $('#imageid').attr( "src", "/new/path/to/image.jpg" );
});
1
  • I think it would be helpful if you told us what files each section of code was in. Are they in the same file, or is the javascript file being included in the header (or somewhere else?)?
    – Corey
    May 20, 2011 at 17:00

3 Answers 3

4

You should try to keep as much HTML out of the PHP as possible like this, hopefully I'm not being to nitpicky...

$(document).ready(function() {
  $('#imageid').attr( "src", "/new/path/to/<?php echo $image_addr;?>" );
});

Also remember that PHP renders on the server before javascript (which renders in the browser), so if you are trying to make a PHP change to a page that is already loaded, that won't work.

4
$(document).ready(function() {
  $('#imageid').attr( "src", '<?php echo "user/hangout_images/$imag_addr"; ?>' );
});
4
  • 1
    @harsh This would only work when the javascript it within the php file. If the javascript is in a .js file, it won't work (unless your server processes .js files as php).
    – Paul DelRe
    May 20, 2011 at 16:40
  • @Neal: you have to surround the php code with quotes; "<?php ... ?>"
    – Toto
    May 20, 2011 at 16:45
  • @M42, there is no reason to do that
    – Naftali
    May 20, 2011 at 16:46
  • @Neal: but you've just modified your answser this way while I submit my comment.
    – Toto
    May 20, 2011 at 16:50
1

If you don't want to put your javascript in with you php I believe you have to use AJAX. This might work..

source.php

$image_addr = "/blah/blah/blah.jpg"
echo $image_addr;

stuff.html (or .js)

    $.get('source.php', setimg);

function setimg(data) {
       $('#imageid').attr( "src", data );
    }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.