Hussein
Hussein

Reputation: 681

How to get Image through ajax jquery?

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');

Upvotes: 3

Views: 6275

Answers (1)

Nel
Nel

Reputation: 574

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>

Upvotes: 3

Related Questions