Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, December 15, 2015

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

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.

Answer by Matt Ball for How to display an image that we received through Ajax call?


You want to send the raw image data base64-encoded, combined with the data:// URI scheme.

Answer by JW. for How to display an image that we received through Ajax call?


So it sounds like there is a URL, and it's /images/25.

As far as I know, you can't display image data that you get from an AJAX call*. But why not just put the URL in an tag? It doesn't matter to the browser that the image is generated by the server, rather than read from a file.

*EDIT: I was wrong; see gideon's answer if you really need to use an AJAX call (e.g. you need to make a POST request, or send certain headers).

Answer by chris for How to display an image that we received through Ajax call?


I'd bank on it being the same as if you rendered if via PHP or ASP or whatever. just something simple like

$('#elementOfChoice').append('something');  

though I could be wrong. All depends on whats happening behind the scenes to make that image become what it is. If its gotta pass through a PHP file cause its a base_64 image and needs to be encoded, or whatever the case then that has to be done accordingly.

Answer by gideon for How to display an image that we received through Ajax call?


To expand on Matt's answer, if you are getting base64 data. You could do something like this:

You need a blank image

  

And then

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

See this MDN reference for more in base64. I made a short demo here: http://jsfiddle.net/99jAX/1/

Answer by Washeen for How to display an image that we received through Ajax call?


$( "" ).attr( "src", icon_url ).appendTo( "#images" );


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 71

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.