Jquery

Loading image through Ajax?

Loading image through ajax! Is it possible? I thought it is possible before i really need to implement it. During some project there was a requirement to load a gif image through ajax. So i just simply tried

$('#popup-container').click(function() {
  $.ajax({
    type: "GET",
    url: "img/popup_calculating.gif",
    dataType: "image/gif",
    success: function(img) {
      i = new Image();
      i.src = img;
      $(this).append(i);
    },
    error: function(error, txtStatus) {
      console.log(txtStatus);
      console.log('error');
    }
  });
});

But rather then getting  a image what i get was error !! It was parsererror. It mean browser is making request asynchronously and getting the data but its not able to understand the returned data. Because the dataType supported by ajax are  xml, html, script and json.

So what should i do? I should think how browser load images when i do something like this

<img title="myimage" src="myimage.png" alt="" >

Browser send the request to url specified in src property of img tag and load image asynchronously with image/png specified in contentType header request but in case of ajax it only accept xml, html, script, and json datatype.
So what should i do!! Think?

When browser already loading images asynchronously then why don’t i use that functionality. Just create a img tag on the fly and put the src property to url. Yeah i got the solution. So here is simple jquery plugin to load image asynchronously.

$.fn.image = function(src, f) {
  return this.each(function() {
    var i = new Image();
    i.src = src;
    i.onload = f;
    this.appendChild(i);
  });
}

Simply put this code in script tag or in js file. And to load image in a container call the image() function like this

$("div#container").image("oganges.jpg",function(){
  alert("The image is loaded now");
});

That’s it!

Standard