Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an image that we received through Ajax call?

Web server generates images and sends them to client directly. There are no URLs to the images, for security reasons. For example, if I enter /images/25 URL in the browser server will send it and browser will download it.

Now I want to get this image from Ajax call and then display it on existing page. I can get the image data. My question is: how can I display an image?

$.get("/images/25", function (rawImageData) {
   // ??? Need to add an image to DOM
});

Update

I apologize for being so stupid. Thank you, JW. Of course I can just put img tag with src to my URL. It does not matter if this is a direct URL to an image file or the server sends it dynamically.

like image 851
Evgenii Avatar asked Mar 01 '12 05:03

Evgenii


People also ask

How do you check if AJAX call is completed?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

What happens during an AJAX call?

When you make an AJAX request, your browser sends an HTTP request to a given address. The server on the other end of the request responds, and returns the data to your browser. This is the same thing that happens when you navigate to a new web page.


1 Answers

To expand on Matt's answer you could use base64 encoded img urls. This is an example from wikipedia of what that img tag would look like:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
 AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
 9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

You need a blank image:

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

Your server needs to return the image as a base64 string, then you could do:

$.get("/images/25", function (rawImageData) {
      $("#target").attr("src","data:image/gif;base64," + rawImageData);
});

See this MDN reference for more in base64 encoded img urls.

I made a short demo here: http://jsfiddle.net/99jAX/1/

like image 149
gideon Avatar answered Oct 26 '22 13:10

gideon