AJAX GET Image Example
In this lesson, we will see how to get an image using ajax XMLHttpRequest object. When you click on button get the XMLHttpRequest object to get image from server and display on current page.
Following are easiest example for fetching image from server. Image response type is BLOB so directly we can not get this image. Response text must be convert into encoding format using user define encode64 function.
Example Code
<html>
<body>
<script language="javascript" type="text/javascript">
function send_with_ajax( ){
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(exception) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("Your browser does not support XMLHTTP Request...!");
}
xhr.open("GET", "300x300.gif", true); // Make sure file is in same server
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
if ((xhr.status == 200) || (xhr.status == 0)){
var image = document.getElementById("get_img");
image.src = "data:image/gif;base64," + encode64(xhr.responseText);
}else{
alert("Something misconfiguration : " +
"\nError Code : " + xhr.status +
"\nError Message : " + xhr.responseText);
}
}
};
}
function encode64(inputStr){
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var outputStr = "";
var i = 0;
while (i> 2;
var enc2 = ((byte1 & 3) << 4) | (byte2 >> 4);
var enc3, enc4;
if (isNaN(byte2)){
enc3 = enc4 = 64;
} else{
enc3 = ((byte2 & 15) << 2) | (byte3 >> 6);
if (isNaN(byte3)){
enc4 = 64;
} else {
enc4 = byte3 & 63;
}
}
outputStr += b64.charAt(enc1) + b64.charAt(enc2) + b64.charAt(enc3) + b64.charAt(enc4);
}
return outputStr;
}
</script>
<button onClick="send_with_ajax()">Get Image</button><br />
<img id="get_img" />
</body>
</html>