Use AJAX for a PHP generated image

Aludaan
Aludaan used Ask the Experts™
on
I am using PHP to create a image and at this moment in time calling it in to HTML using a img tag.
<img src="test.php">

In the PHP file I am basically taking some transparant png files and changing the color based off the customers selection and overlaying it on a background color also based off a users selection. Then returning that final image to the HTML file. So for example all my png files are black and transparant and my background images are solid colors (red, blue, green, etc). So the customer may select a yellow png on a green background. I transform my black png into a yellow then overlay it on the green background and return that image.

My problem comes in that this process usually only takes a very short time (less than a second) but on occasion the server can take a few seconds to return the image, or on some peoples PCs they say they can see up to a 5 second delay before they see anything take effect. Because of this I would like to load the image using AJAX and if the image isn't ready then use a now loading logo.

I have used AJAX before but I can't figure out how to do this though. Usually you would hand AJAX a script you want to run in the background, in this case test.php which would make the image. And you would take the output that is returned and display it using a innerHTML for example. But because PHP is creating a temporary image it is a image being handed back. How can I display that when it is ready? Is there another method I could use?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Hi Aludaan,

you only need to change the src value of <IMG> at runtime.
make your script accept the get parameters so that you can say some thing like

test.php?background=black.png&overlay=green.png

Make sure that above url return the new image.

now here is your code.

<img id="some_id" src="" />

document.getElementById('some_id').src = "test.php?background=black.png&overlay=green.png";

This will make your image load at runtime
What are the names&functions of all the files related to this? I am curious to know your user input files names and the PHP processing files names.

AJAX requests are usually for the HTML/XML content inside a file which is either STATIC(ie: edited by you and uploaded onto the server) or DYNAMIC PHP OUTPUT(ie: made at runtime by other variables and inputs). You cannot AJAX an image onto a page, because the output from the "test.php" file is Image Data (I am guessing this is what the test.php file does, probably in the format of a PNG as well right?)

But not to fret! There are ways to "preload" images onto the webpage. And there are some pretty advanced image preloader Javascripts out there (I used this one a few weeks back for a client who wanted a gallery of images but wanted some stylish effects while the images were loading http://www.roscripts.com/Javascript_image_preloader-111.html). All you have to do is add the <img src="test.php" /> into your <HTML><BODY> like you normally do always and add that javascript code onto the page.

Just read that blog and itll tell you how to use it! I hope it helps!
Oh and change these settings in the Javascript file to make it work with your image
/* */
// You may modify the following:
	var locationAfterPreload = "http://www.yourwebsite.com/output.htm" // URL of the page on which there is the <img src="test.php"> tag showing the final image after they have submitted the data.
	var lengthOfPreloadBar = 150 // Length of preload bar (in pixels)
	var heightOfPreloadBar = 15 // Height of preload bar (in pixels)
	// Put the URLs of images that you want to preload below (as many as you want)
	var yourImages = new Array("http://www.yourwebsite.com/test.php"); //dont worry that the extention is not .php

Open in new window

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

http://www.dynamicdrive.com/dynamicindex4/preloadit.htm Same script but with better explaination.

Differant script which is newer, I havent tried it out myself but its by the same people as the first script, http://www.dynamicdrive.com/dynamicindex4/preloadimage2.htm

Author

Commented:
To be clear, the background image and png images are all stored on my server. None are uploaded by the user.

There is a drop down box that has color names. One for the background color, one for the png color. When you select either one, using javascript it automatically calls the test.php immediately which does the color changes requested and then replaces the current image with the new one. ie when clicked "<img src='test.php'>" becomes "<img src='test.php?bgcolor=green&pngcolor=red'> using javascript to replace the src name. That means that the whole page does not reload so it can't be a preload. And because the user can select any combination of colors the images can't be premade and waiting on the server so any preloading is out.

As I said though, it works fine the way it is, it can just be delayed sometimes and I would like to have a refresh logo showing instead of the user thinking the site is hanging.
OH alright I understand what you are doing now. Sorry I had some other way of doing it in my mind before.

Is the Image output of "test.php" transparent at all? Or fully opaque. If it is opaque you can do some crafty CSS to make the image look like its loading.

First: since you are using javascript to replace the "src" name I am assuming you have an "id" or "name" in your <img>.

Second: in your javascript code which changes the src of the said image. Make it load up the image named "blank.gif" (which is just a 1x1 pixel transparent image which I will attach with this post) JUST before you set the src to the "test.php?etcetcetc". This is done so that the background image which is set to "loading.gif" which is an Ajax loading image to give the illusion that while the next image is being prepared and loaded it will show the loading.gif in the middle of where the image will appear.

I have attached the 2 images in a zip file onto this post. I got the ajax image from this website, http://www.ajaxload.info/ its easy to use and its free to use images no loyalties.
<html>
<head>
<style>
img.loading {
	background-image:url('loading.gif');
	background-position:center center;
}
</style>
</head>
<body>

<script>
function yourFunction() {
	//part where it calculates all the extra stuff to add to the image src URL;
	document.getElementById("phpImg").src = "blank.gif";
	document.getElementById("phpImg").src = "test.php?etcetcetc that your javascript added";
}
</script>

<img class="loading" src="test.php" id="phpImg" width="200" height="50">

</body>
</html>

Open in new window

images.zip
Things to note:

The CSS class tag.

Note how I set a width and height for the image.
You should set the width and height in the <img> of the image outputed from "test.php" manually for things to go smoothly for this little trick.

Note how in my example javascript code that i loaded "blank.gif" as the image's src on the line just BEFORE i loaded the actual image src that it should be.

Try this out. I hope it works
Slight modification.. Whoops I forgot about the CSS background image being repeated before.
<style> 
img.loading { 
        background-image:url('loading.gif'); 
        background-position:center center;
        background-repeat:no-repeat;
} 
</style>

Open in new window

Here I have attached another bit of code showing just what I have told you but implemented by my own function. Try saving this onto a .htm file in the same folder as "blank.gif" and "loading.gif" and after that open the .htm file with IE or FireFox and try clicking on the Image to make it load the second image. This is what it will look like in action if you do the steps I told you.
<html> 
<head>
<title>SleepinDevil's Crafty Trick To "Emulate" Image Loading</title>
<style> 
img.loading { 
        background-image:url('loading.gif'); 
        background-position:center center;
        background-repeat:no-repeat; 
} 
</style> 
</head> 
<body> 
 
<script> 
function myFunction() { 
        document.getElementById("phpImg").src = "blank.gif"; //to make the image the transparent "gif" so the background loading picture is visible while the actual image we want to load is being loaded by the browser
        document.getElementById("phpImg").src = "http://www.travelblog.org/Wallpaper/pix/tb_turtle_diving_sipadan_malaysia.jpg"; 
} 
</script> 
 
<img class="loading" src="http://www.travelblog.org/Wallpaper/pix/tb_fiji_sunset_wallpaper.jpg" id="phpImg" width="500" height="500" onclick="javascript:myFunction();"> 
 
</body> 
</html>

Open in new window

Arrrg I tried it on FireFox and it isnt working the same way I want it to on IE, but I changed the code and now it works... Its abit more complicated now but I hope you will understand how to adopt it onto your design.
<html> 
<head> 
<style> 
img.loading { 
        background-image:url('loading.gif'); 
        background-position:center center; 
} 
</style> 
</head> 
<body> 
 
<script> 
function yourFunction() { 
        //part where it calculates all the extra stuff to add to the image src URL; 
        document.getElementById("phpImg").src = "blank.gif"; 
        window.setTimeout('document.getElementById("phpImg").src = "test.php?etcetcetc that your javascript added";', 100);
} 
</script> 
 
<img class="loading" src="test.php" id="phpImg" width="200" height="50"> 
 
</body> 
</html>

Open in new window

If you could attach your code for your page or zip it and upload it here, then I could addon my bits of the code onto your design and make it work.

If you have any more questions please do ask. Also I am really sorry about all the comments, I wish it were possible to delete/edit comments here instead of adding more onto it.

Author

Commented:
This almost did the trick. There is 1 problem with it that I don't think I mentioned. The size of the box can actually grow past it's starting image size. So I can't put the height and width in the img tag. The width is constant so I added that or it wouldn't work at all. But if I put in the height it would squish the image. But without me putting that in every time the page refreshes the image expands to almost twice it's height until it gets the image back and then snaps back to the correct size.

At this point I have basically tabled this and I may just put a warning over the image that it can take a few seconds to load and to be patient. This will probably end up being redone once I learn flash a bit better anyway.

Thanks Sleepin, you still get the points because your idea rocked. This should definitely be saved!
What is roughly the normal/smallest height of the image the PHP page creates?

If you were able to edit the blank.gif so that it matches that height and width then you can remove the "width" and "height" attribute completely from the <img> tag, which inturn stops the issues with the massive page height because the width was set manually. But remember you need a image editor capable of editing transparent GIF images to do this (MSPaint will not work right).

I could edit and send back the "blank.gif" to meet the size requirements you need if you want to try out this option still.

Otherwise, no worries I had fun writing all that out anyway. If you are to use Flash, let me tell you, the end result will look AWESOME but it might be a long haul to get the results you are after, but it would an interesting thing to do! Good luck whichever path you follow! Thanks for the points!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial