3

I want to display image by ajax jquery in this way so is that possible?

$.ajax({  
    url: "c.jpeg",
    type :"get",
    dataType: "image/jpeg",

    success: function(data)
    {

      $("#myimg2").attr("src",data);
    }

   })

and this is the html

<body>
<img id="myimg2" ><br>
</body>

If that could be possible in some way. I want also to get the image from php file rather than directly jpeg file using this header.

header('content-type: image/jpeg');
aesede
  • 5,541
  • 2
  • 35
  • 33
Hussein
  • 653
  • 3
  • 10
  • 28
  • 2
    http://stackoverflow.com/questions/17657184/using-jquerys-ajax-method-to-retrieve-images-as-a-blob – Musa Dec 26 '15 at 01:27
  • @Hussein _"want to display image by ajax jquery"_ What is purpose of using ajax , jQuery ? – guest271314 Dec 26 '15 at 01:37
  • I want to update the image automatically by a poll function in ajax. And the image is coming from mysql database in php file, finally will receive that php file as an image file using header('content-type: image/jpeg'); – Hussein Dec 26 '15 at 01:44
  • 1
    @Hussein How frequently should image be updated ? – guest271314 Dec 26 '15 at 01:48
  • It depends on database values and could be every 3 seconds or less – Hussein Dec 26 '15 at 01:50
  • 2
    You don't need ajax for this, just use a regular image tag, and append a timestamp to the url every three seconds to update it. – adeneo Dec 26 '15 at 01:56
  • 1
    One approach could include using `setTimeout` , `jQuery.ajax()` , return image as `data URI` from server , which would not require additional conversion to `objectURL` at browser ; could use existing `$("#myimg2").attr("src",data);` – guest271314 Dec 26 '15 at 01:57
  • @adeneo yeah you are right I have tried that but it is not working on java webView Android studio – Hussein Dec 26 '15 at 02:00
  • @guest271314 I have the image comming from mysql database not server – Hussein Dec 26 '15 at 02:01
  • 1
    @Hussein _"have the image comming from mysql database not server "_ Yes, "mysql database" is server to client browser ? Try converting image to `data URI` at database , return `data URI` string to `$.ajax()` – guest271314 Dec 26 '15 at 02:03
  • Could you please help me out with this coz I have no idea, what I am doing now is retrieve the image as blob and display it at the php using header('content-type: image/jpeg'); – Hussein Dec 26 '15 at 02:05
  • 1
    @Hussein See http://php.net/manual/en/wrappers.data.php , https://davidwalsh.name/data-uri-php , http://www.paulund.co.uk/convert-image-base64-php , https://gist.github.com/FlyingTopHat/3661056 – guest271314 Dec 26 '15 at 02:06

1 Answers1

3

Please, try this. It works for me.

$.ajax({
   url: "path/to/img.jpg",
   xhrFields: {
      responseType: 'blob'
   },
   success (data) {
      const url = window.URL || window.webkitURL;
      const src = url.createObjectURL(data);
      $('#image').attr('src', src);
   }
});
<div>
  <img id="image">
</div>
Nel
  • 454
  • 5
  • 14