Skip to content

banner ajax
The Complete Reference: Ajax

Examples: Data URI

Note: This example does not work for Internet Explorer 7 and earlier

Data URI Example


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 4 : Data Types - Data URI </title>
<script type="text/javascript">
 
 
function encodeValue(val)
{
 var encodedVal;
 if (!encodeURIComponent)
 {
   encodedVal = escape(val);
   /* fix the omissions */
   encodedVal = encodedVal.replace(/@/g, '%40');
   encodedVal = encodedVal.replace(/\//g, '%2F');
   encodedVal = encodedVal.replace(/\+/g, '%2B');
 }
 else
 {
   encodedVal = encodeURIComponent(val);
   /* fix the omissions */
   encodedVal = encodedVal.replace(/~/g, '%7E');
   encodedVal = encodedVal.replace(/!/g, '%21');
   encodedVal = encodedVal.replace(/\(/g, '%28');
   encodedVal = encodedVal.replace(/\)/g, '%29');
   encodedVal = encodedVal.replace(/'/g, '%27');
 }
 /* clean up the spaces and return */
 return encodedVal.replace(/\%20/g,'+'); 
}
 
function createXHR()
{
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
 
   return null;
}
 
function sendRequest(form)
{
    var xhr = createXHR();
 
    if (xhr)
     {
       var url = "http://ajaxref.com/ch4/processimage.php";
       var payload = "image=" + encodeValue((form.responseType.options[form.responseType.selectedIndex].text).toLowerCase() + ".png");
       xhr.open("GET",url + "?" + payload,true);
       xhr.onreadystatechange = function(){handleResponse(xhr);};
       xhr.send(null);
     }
}
 
function handleResponse(xhr)
{
  if (xhr.readyState == 4  && xhr.status == 200)
    {
        var responseImage = document.getElementById("responseImage");
        responseImage.src = "data:image/png;base64," + xhr.responseText;
        responseImage.style.display = ""; 
    }
}
</script>
 
</head>
<body>
<h3>Data URI Example</h3>
<form>
    <label>Pick a flag:
  <select name="responseType">
      <option>USA</option>
    <option>Italian</option>
    <option>Japanese</option>
  </select></label>
 
<input type="button" value="Send" onclick="sendRequest(this.form);" />
</form>
<br />
<img id="responseImage" alt="" border="1" style="display:none;" />
</body>
</html>