0

I would like to know, how i can show a image through my javascript code.

Example:

javascript.php:

echo '<script type="text/javascript" src="http://domain.com/show_image.php"></script>';

show_image.php:

echo '<img src="http://domain.com/image/show_image.png" />';

This will not show anything. Anyone know why? :)

1
  • You can simply show the image including your php file with include('show_image.php'); Commented Feb 16, 2011 at 12:41

3 Answers 3

2

That should be:

echo 'document.write("<img src=\"http://domain.com/image/show_image.png\">")';

above assumes proper content-type for response

header('Content-type: text/javascript', true); 
Sign up to request clarification or add additional context in comments.

5 Comments

I need to do it in a <script>, any ideas?
This would probably generate invalid XHTML because the <img> would be added after the closing </html>, no?
It all depends on where the script tag is placed, if I understand correctly, document.write drops the added content where the script tag is.
You don't need to give that second argument to header(), as it defaults to TRUE.
@Dre, yes, scripts are executing in-place, unless defer attribute is set.
1

Because script elements are not designed to show images.

Use include 'show_image.php'.

1 Comment

I need to do it in a <script>, any ideas?
1

Assuming you want the <img> to appear where the <script> is, first change the <script> to something like this:

<script id="imagePlace" type="text/javascript" 
  src="http://domain.com/show_image.php"></script>

Then change show_image.php to this:

var scr = document.getElementById('imagePlace');
var img = document.createElement('img');
img.setAttribute("src","http://domain.com/image/show_image.png");
scr.parentNode.insertBefore( img, scr );

1 Comment

Hello Andrew. I tried this solution, but without luck: echo '<script type="text/javascript"> var scr = document.getElementById(\'imagePlace\'); var img = document.createElement(\'img\'); img.setAttribute("src","domain.com/image.png"); scr.parentNode.insertBefore( img, scr ); </script>';

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.