AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 35


PART I


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 = "http://ajaxref.com/ch2/imagegenerator.php";
/* 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 += "×tamp=" + encodeValue(timeStamp);

/* get target div to show result */
var target = document.getElementById("resultDiv");

/* clear target div for response */
target.innerHTML = " ";

/* set up status image */
var statusImg = document.createElement("img");
statusImg.id = "progressBar";
statusImg.border=1;
statusImg.src = "progressbar.gif";
target.appendChild(statusImg);
/* submit rating */
sendRequest(url, payload, target, timeout);
/* return false to kill form post */
return false;
}
</script>
</head>
<body>
<form action="http://ajaxref.com/ch2/imagegenerator.php"
method="get" onsubmit="return getImage(this.username.value);">
<label>Enter your name:
<input type="text" name="username" size="20" maxlength="20" /></label>
<input type="submit" value="Generate" />
</form>
<br />
<div id="resultDiv"> </div>

</body>
</html>
Free download pdf