S
S
serf102021-03-27 22:34:33
AJAX
serf10, 2021-03-27 22:34:33

How to display image returned by Ajax request in img tag?

There is such a request. We pass authorization. As a result of the request, we get the image image/png

$.ajax({
  url: MY_URL_,
  method: "GET",
  contentType: "image/png",
  headers: {
    "Authorization": "Basic YAZRt45aWDa25wDDdFND232YFmVmb23213ffWEa5OA=="
  }
}).then(response => {
    console.log(response);
}).catch(error => {
   console.log(error);
})


and there is html code

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ajax image demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<h1> Hello</h1>

<div id="frame">
<img id="canvas" />
</div>
 
 
</body>
</html>


consloe.log(response) outputs something like this to the console:
605f87de3f20e366636260.png

Question: how to display on the page and stuff into img what response returns ? is it possible to encode it for base64 or something else?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitriyq, 2021-03-27
@serf10

Add to ajax config and display image via URL.createObjectURL
xhrFields:{ responseType: 'blob' }

$.ajax({
  url: MY_URL_,
  method: "GET",
  xhrFields: {
    responseType: 'blob'
  },
  headers: {
    "Authorization": "Basic YAZRt45aWDa25wDDdFND232YFmVmb23213ffWEa5OA=="
  }
}).then(response => {
    console.log(response);
    $('#canvas').attr('src', URL.createObjectURL(response));
}).catch(error => {
   console.log(error);
})

O
Oleg, 2021-03-27
@lolzqq

- you can generate a picture every time with a get request with the parameters you need with a php script using the gd library
- using a script that processes ajax - send a url to the script that generates an image
- receiving this url in the response - insert it as the src attribute of the img tag - the picture is loaded from the server
alternatively, if you just have a set of ready-made images
- a script that processes your ajax request - returns the url of the desired image
- receiving this url in the response - insert it as the src attribute of the img tag - the image is loaded from the
server canvas can be done like this:

var canvas=document.querySelector('#canvas');
var img = new Image();
img.src = "face.jpg";
img.onload = function() {canvas.drawImage(img, 10, 10);}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question