harsh
harsh

Reputation: 131

how to write php variable inside a javascript code

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" );
});

Upvotes: 2

Views: 5341

Answers (3)

mazlix
mazlix

Reputation: 6263

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 );
    }

Upvotes: 1

Naftali
Naftali

Reputation: 146302

$(document).ready(function() {
  $('#imageid').attr( "src", '<?php echo "user/hangout_images/$imag_addr"; ?>' );
});

Upvotes: 4

Corey
Corey

Reputation:

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.

Upvotes: 4

Related Questions