Solved

Dynamic Image using jQuery/Ajax and PHP

Posted on 2009-04-14
3
2,213 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

757 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

19 Experts available now in Live!

Get 1:1 Help Now