How do I load an image using jquery?

I am currently working on a class that generates charts as images from php. I want to load these images dynamically using jquery. How can i do this?? I won't have a real image file, just the content of the file when I call it with ajax ... And I can't just define the php script as src because I need to pass Post parameters to the image ...

EDIT:

Okay. I think I need to explain this a little further ...

Here is the html code:

<div>
<img id="image" />
</div>
<input type="button" onclick="loadPicture();" />

      

When the button is clicked, some data needs to be sent to the PHP script that generates the image. A callback function or something similar should now send the image to the img element. Just placing the image in the img tag doesn't work. The following code will work, but how can I add POST parameters?

<img src="<scriptname>.php" />

      

+1


source to share


4 answers


Http POST requests are not meant to return resources. Why aren't you using a GET request? The "REST" way to do this is to create an image with a POST request and then load it with a GET request. You need to define a URL mapping for your resources.



+3


source


No people! You basically have 3 options as I see it.

Method 1 - Insert Image

Do what Brian said, but your imagedata

needs to be base64 encoded .

$("#div").html(data); // instead of this
$('#image').attr('src','data:image/gif;base64,'+data); // try something like this

      

But I don't like the idea of ​​embedding an image or passing post data. Base64 can get a little big for large images.



Method 2 - Save Image

You can $.post

data as before, then save the image and return the image url.

Method 3 - Use GET

Modify the generated image script to accept the data GET

. If you have a lot of data to transfer, try compressing it in some way, or perhaps you can use variables SESSION

.

+2


source


I'm not really sure if I understood what you said correctly, but you can use the $ .post () method which would return whatever you need via a callback. Something like that:

$.post("file.php",{param: val},function(data){
    $("#div").html(data);
})

      

If you could explain, maybe we can understand better. Hope this helps.

+1


source


Is there a need to use AJAX / jQuery? Or do you just stick it in because it's cool?

Here's what I will do:

if (isset($_POST['createImage'])){
    // This means that the button was clicked
    // Generate your image, and then display it:
}

// Regardless, you would now show your form
// That way if values were to be changed, the graphic can be recalculated.

      

This way you get the desired result (graphical loading depending on the form output) and one click to generate that output.

0


source







All Articles