What's the proper way to load an image using ajax?
I cannot use the usual <img/> tag as I have to pass some specific http headers to the GET request. For that reason, I'm somewhat limited to using Ajax. The headers that I have to pass to the request are credentials. Without that, it won't be possible to get the image files.
I was wondering if there was a way to make an ajax request to load the data into the img tag and still keep the src attribute as the real url of the image. I'm not too much interested into loading the image using a base64 data url.
Short Answer.... You can't.
The only way you are going to get that image into the <img> tag and still pass specific http headers is via ajax... and the response has to be a base64 data url (or you have to convert it to a base64 data url) that you can put into the <img> tag as the value of the src attribute.
As soon as you change the src attribute of the <img> tag, the browser will request the image from the server... and it won't pass any specific headers.
If you want to display the image, you need either an <img> tag (which gives you the limitations I mentioned) or you can put it as a css background for any element, but the same limitations apply. As soon as you set the url, the browser will load the image without any custom headers passed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With