Solved

Dynamic Image using jQuery/Ajax and PHP

Posted on 2009-04-14
3
2,215 Views
Last Modified: 2012-05-06
Hi,
I have a PHP script that is generating an image based on values passed to the script using jQuery Ajax functionality. Here is the important part of the PHP script;

header('Content-Type: image/jpeg');
imagejpeg($image, 'images/tmp/admin.preview.jpg');
imagedestroy($image);

I can get the image to display just fine without using Ajax. I would prefer not to store the image locally on the server, but instead have the preview image display temporarily in memory. I have the following jQuery code implemented that sends the form data to the PHP script, which generates the dynamic image for preview using jpeg image stream.

$(document).ready(function()
{
        var options = {
                target:     '#preview-wrapper',
                type:           'post',
                cache:          false,
                url:        'admin.preview.php', // return raw jpeg stream (see
above php code)
                success:    function(obj) {
                        // attempted creating an image tag, then pointing to the php script
directly. Neither works properly.
                }
        };
        // pass options to ajaxForm
        $('#formAdmin').ajaxForm(options);
});

Hopefully someone can help answer the following questions;
1) What is the best way to accomplish this task? (i.e. return image stream, return HTML image tag pointing to the locally stored jpeg, etc...)
2) Could someone help me with the jQuery code or any changes I need to make in the php script?

Thanks in advance for any help or direction.
0
Comment
Question by:ecomm
  • 2
3 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 24152726
I think the best approach to the image would be to use imagejpeg() and write the image to the server, then you can use AJAX to update the contents of a DIV so that the image is displayed in the DIV.  Sending the image inline seems problematic to me.  So I would opt to return the HTML image tag.

I'm not conversant in jQuery, but I can show you this thing from my teaching library that strips all of AJAX down to its essentials.   Can't remember where I got it, but since it is signed "Rasmus" I am led to think it is "Lerdorf" of PHP fame.  Read it over and you will see what is going on in the concept of replacing a DIV.

HTH, ~Ray
I find a lot of this AJAX stuff a bit of a hype.  Lots of people have

been using similar things long before it became "AJAX".  And it really

isn't as complicated as a lot of people make it out to be.  Here is a

simple example from one of my apps.  
 

First the Javascript:
 

function createRequestObject() {

    var ro;

    var browser = navigator.appName;

    if(browser == "Microsoft Internet Explorer"){

        ro = new ActiveXObject("Microsoft.XMLHTTP");

    }else{

        ro = new XMLHttpRequest();

    }

    return ro;

}
 

var http = createRequestObject();
 

function sndReq(action) {

    http.open('get', 'rpc.php?action='+action);

    http.onreadystatechange = handleResponse;

    http.send(null);

}
 

function handleResponse() {

    if(http.readyState == 4){

        var response = http.responseText;

        var update = new Array();
 

        if(response.indexOf('|' != -1)) {

            update = response.split('|');

            document.getElementById(update[0]).innerHTML = update[1];

        }

    }

}
 

This creates a request object along with a send request and handle

response function.  So to actually use it, you could include this js in

your page.  Then to make one of these backend requests you would tie it

to something.  Like an onclick event or a straight href like this:
 

  <a href="javascript:sndReq('foo')">[foo]</a>
 

That means that when someone clicks on that link what actually happens

is that a backend request to rpc.php?action=foo will be sent.
 

In rpc.php you might have something like this:
 

  switch($_REQUEST['action']) {

    case 'foo':

      / do something /

      echo "foo|foo done";

      break;

    ...

  }
 

Now, look at handleResponse.  It parses the "foo|foo done" string and

splits it on the '|' and uses whatever is before the '|' as the dom

element id in your page and the part after as the new innerHTML of that

element.  That means if you have a div tag like this in your page:
 

  <div id="foo">

  </div>
 

Once you click on that link, that will dynamically be changed to:
 

  <div id="foo">

  foo done

  </div>
 

That's all there is to it.  Everything else is just building on top of

this.  Replacing my simple response "id|text" syntax with a richer XML

format and makine the request much more complicated as well.  Before you

blindly install large "AJAX" libraries, have a go at rolling your own

functionality so you know exactly how it works and you only make it as

complicated as you need.  Often you don't need much more than what I

have shown here.
 

Expanding this approach a bit to send multiple parameters in the

request, for example, would be really simple.  Something like:
 

  function sndReqArg(action,arg) {

    http.open('get', 'rpc.php?action='+action+'&arg='+arg);

    http.onreadystatechange = handleResponse;

    http.send(null);

  }
 

And your handleResponse can easily be expanded to do much more

interesting things than just replacing the contents of a div.
 

-Rasmus

Open in new window

0
 
LVL 3

Author Closing Comment

by:ecomm
ID: 31570255
I ended up using a jQuery based Ajax solution, but thanks for providing help.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24348703
Thanks for the points - it's a great question. ~Ray
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now