Skip to content

banner ajax
The Complete Reference: Ajax

Examples: Image Generator


 
<!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=iso-8859-1" />
<title>Chapter 2 : Image Generation</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 sendRequest(url, payload, target, status, timeout)
{
    /* clear target div for response */
    target.innerHTML = "&nbsp";
    
    /* show network status if specified */
    if (status.show)
      {
         if (status.type == "text")
          {
            var statusDiv = document.createElement("div");
            statusDiv.id = "statusDiv";
            statusDiv.innerHTML = status.message;
            target.appendChild(statusDiv);
           }
        else if (status.type == "img")
               {
                   var statusImg = document.createElement("img");
                statusImg.id = "progressBar";
                statusImg.border=status.border;
                statusImg.src = status.src;
                target.appendChild(statusImg);
               }
     }
 
    /* create request object */
    var currentRequest = new Image();
 
    /* timeout variable set later */    
    var timer;
    
    currentRequest.onerror = function(){cancelRequest(target,'Server error',currentRequest,timer);}; 
    
    /* register callback upon load success */
    currentRequest.onload = function(){handleResponse(target,currentRequest,timer);};
 
    /* start request */
    currentRequest.src = url+"?"+payload;
    
    /* function to cancel request if network timeout occurs */
    networkTimeout = function(){cancelRequest(target,'Network timeout',currentRequest);};
    
    /* define network timeout in milliseconds and bind to timeout function */
    var timer = setTimeout("networkTimeout()",timeout*1000); 
}
 
function cancelRequest(target, message, currentRequest,timer)
{
    /* clear timer */
    if (timer) 
      clearTimeout(timer);
      
    /* clear callback */  
    currentRequest.onload = null;
    
    /* set message indicator if any */
    target.innerHTML = message;
}
 
function handleResponse(target,newImage,timer)
{
    //clear network timeout timer
    if (timer) 
      clearTimeout(timer);
      
    target.innerHTML = "Here is your custom image:<br /><br />";
    target.appendChild(newImage);
}
 
function getImage(userName)
{
    /* URL of server-side program to create custom image */
    var url = "https://ajaxref.com/ch2/imagegenerator.php";
 
    /* Set communication status display options */
    var status = {'show': true, 'type': 'text', 'message': 'Image creation in progress...'};
 
    /* Make timestamp to prevent caching */
    var timeStamp = (new Date()).getTime();
 
    /* Define a timeout to give up in case of network problem */
    var timeout = 5;
        
    /* Form payload with escaped values */
    var payload = "username=" + encodeValue(userName);
    payload += "&timestamp=" + encodeValue(timeStamp);
 
    /* get target div to show result */
    var target = document.getElementById("resultDiv");
 
    /* submit rating  */
    sendRequest(url, payload, target, status, timeout);
    
    /* return false to kill downgrade communication */
    return false;
}
 
window.onload = function () {document.imageForm.onsubmit = function() { return getImage(this.username.value);}}
</script>
 
</head>
<body>
 
<form name="imageForm"  action="https://ajaxref.com/ch2/twoway/applied/imagegenerator/imagegenerator.php" method="get" target="_blank">
      
 <label>Enter your name:
 <input type="text" name="username" size="20" maxlength="20" /></label>
<noscript>
 <input type="hidden" name="transport" value="downgrade" />
</noscript>
 <input type="submit" value="Generate" />
</form>
<br />
<div id="resultDiv">&nbsp;</div>
</body>
</html>