[jquery] Display PNG image as response to jQuery AJAX request

Is it possible to display an image returned by jQuery AJAX call, in the main stream of your HTML?

I have a script that draws an image with a header (image/PNG). When I simply call it in the browser, the image is displayed.

But when I make an AJAX call with jQuery on this script, I can't display a clean image, I have something with a lot of strange symbols. This is my script that makes the image with a header (image/PNG).

#!/usr/bin/perl 

use strict;
use CGI;
use Template;
use CGI::Carp qw(fatalsToBrowser);
use lib qw(lib);
use GD;

my $cgi    = new CGI;

my $id_projet            =  $cgi   -> param('id_projet') ;      # 

# Create a new image
my $image = new GD::Image(985,60) || die;
my $red =  $image->colorAllocate(255, 0, 0);
my $black =  $image->colorAllocate(0, 0, 0);

$image->rectangle(0,0,984,59,$black);
$image->string(gdSmallFont,2,10,"Hello $id_projet ",$black);
# Output the image to the browser

print $cgi -> header({-type => 'image/png',-expires => '1d'});

#binmode STDOUT;

print $image->png;

Then I have my main script with an AJAX call inside:

  <script type="text/javascript" > 

  $(document).ready( function() { 

  $.ajax({
  type: "POST",
  url:'get_image_probes_via_ajax.pl',
  contentType: "image/png",
  data: "id_projet=[% visual.projet.id %]",
  success: function(data){
  $('.div_imagetranscrits').html('<img src="' + data + '" />'); },
 } );

 </script>  

In my HTML file I have one div with class="div_imagetranscrits" to be filled with my image.

I don't see what I'm doing wrong. The other solution is to make my script write the image on disk and just get the path to include in the src to display it. But I was thinking it was possible to get the image with an image/PNG header directly from an AJAX request.

This question is related to jquery ajax image header request

The answer is


This allows you to just get the image data and set to the img src, which is cool.

var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );        
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
    var blob = oReq.response;
    var imgSrc = URL.createObjectURL( blob );                        
    var $img = $( '<img/>', {                
        "alt": "test image",
        "src": imgSrc
    } ).appendTo( $( '#bb_theImageContainer' ) );
    window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );

The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.


Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown? No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll

Examples related to request

How to send Basic Auth with axios How to post raw body data with curl? Pandas read_csv from url POST request with a simple string in body with Alamofire PHP GuzzleHttp. How to make a post request with params? How to modify the nodejs request default timeout time? Doing HTTP requests FROM Laravel to an external API CORS jQuery AJAX request Node.js request CERT_HAS_EXPIRED What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)