How to use ajax to set the src of an image?

mehulkar picture mehulkar · Mar 30, 2015 · Viewed 10k times · Source

I need to set some headers when getting an image. The img src attribute does not allow this, so I'm using an XHR request to get the image. However, when I set the src attribute on the img tag after that request completes, it looks like the request is triggered again. Is there a way to cache the image and not trigger the second request?

Sample Code:

$(document).ready(function() {
    var url = 'https://i.imgur.com/bTaDhpy.jpg'
    var file = $.get(url);
    file.then(function(data) {
        $('#foo').attr('src', url);
    });
});

JS Fiddle: https://jsfiddle.net/mehulkar/o4Lcs5Lo/

Note: my question is not about how to set the appropriate headers in the xhr request. My question is how to not trigger another GET from the setting of the src attribute and use the response from the XHR to display the image.

Answer

RWAM picture RWAM · Mar 30, 2015

Use the $.ajax for this:

var myImg = $('#foo'),
    mySrc = 'https://i.imgur.com/bTaDhpy.jpg';

$.ajax({
    url: mySrc,
    type: "GET",
    headers: {
        "X-TOKEN": 'xxxxx'
    }
}).done(function() {
    myImg.attr('src', mySrc);   // set the image source
}).fail(function() {
    myImg.hide();    // or something other
});