Handling images from XMLHttpRequest (with HTML and Javascript)

By | January 12, 2018
Questions:

I am using an XMLHttpRequest to fetch an image from a server (run locally from a third party server-applet)

A simplified version of the code is shown below.

The image is returned as a JPEG and the returned header shows “content-type= image/jpg”. I can view the information via Firebug for Firefox.

However I am having a terrible time being able to show the actual image on a webpage because it is the image data being returned from the server NOT a uri to the image location.

What is the proper way to display this image from the returned data? Should I be using a <span> tag or an <img> tag or a <magical-show-image-from-data> tag?

function getXML(url, postData, requestStateChangeHandler){        
    if(window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {//Code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = requestStateChangeHandler;

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
    xmlhttp.send(postData);
}


function requestStateChangeHandler(){
    if (xmlhttp.readyState == 4) 
    {
        if(xmlhttp.status == 200)
        {
            document.getElementById('results').innerHTML = xmlhttp.responseText;
        }
        else
            dump("Error loading page\n");
    }
}
Answers:

You can use inline images

on server side encode your response in base64

in php use base64_encode("your data")
and in javascript

result = document.getElementById('results');
result.innerHTML = '<img src="data:image/gif;base64,' + xmlhttp.responseText + '"/>';

Questions:
Answers:

W3C is working on File API and XMLHttpRequest Level 2 to provide a unified experience with Blob for your requirement. You may want to investigate if any existing browser has implemented this feature.

Questions:
Answers:

Seems like the easiest thing to do would be to set up a local proxy service that you can access via a GET and URL parameters, and on the back end it does the POST to the original image service, receives the image data back, and passes it back to you. Then you just put the URL of your proxy (with parameters) into the img src attribute.

<img src="http://myproxy/foo.jpg?param1=bar&param2=baz" />

The proxy at myproxy POSTs a request to the image servlet accordingly.

Questions:
Answers:

Do you have to use Ajax? Why not just add an image to your DOM? When I type the following code in to my debugger in chromium it appends the PHP logo to the current page:

document.body.appendChild(document.createElement('img')).setAttribute('src', 'http://static.php.net/www.php.net/images/php.gif');

?

Leave a Reply

Your email address will not be published. Required fields are marked *