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

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

Now I want to get this image from an Ajax call, and then display it on an existing page. I can get 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. Thanks, JW. Of course, I can just put the img tag with src in my URL. It does not matter if this is the direct URL of the image file or whether the server sends it dynamically.

+7
source share
5 answers

So it looks like there is a url, and /images/25 .

As far as I know, you cannot display image data obtained from an AJAX * call. But why not just put the url in the <img> ? It does not matter for the browser that the image is generated by the server, but not read from the file.

* EDIT: I was mistaken; see gideon answer if you really need to use an AJAX call (for example, you need to make a POST request or send specific headers).

+4
source

To deploy Matt's answer, you can use base64 encoded img urls. This is an example from wikipedia of what the img tag will 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="" /> 

The server needs to return the image as a base64 string, and then you can:

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

See this MDN link for more base64 encoded img urls.

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

+18
source

You want to send base64-encoded raw image data in combination with data:// URI .

+5
source

I would call it the same as if you were displayed, if through PHP or ASP or something else. just something like

 $('#elementOfChoice').append('<img src="'+ rawImageData +'" alt="something" />'); 

although I could be wrong. It all depends on what happens behind the scenes to make this image what it is. If it needs to go through a PHP file, you will get its base_64 image and should be encoded or something in this case, it should be done accordingly.

+1
source
 $( "<img>" ).attr( "src", icon_url ).appendTo( "#images" ); 
-one
source

All Articles