AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 345


<input type="file" name="uploadedFile" /><br />
<input type="submit" name="uploadButton" id="uploadButton" value="Upload" />
<div id="status"><div class="bar" id="bar" style="display:none;"><div
id="barStatus"></div></div><span id="statusSpan"></span></div>
</form>

Upon page load, a handler is bound to start the monitor of the file upload.

window.onload = function ()
{
document.requestForm.action="http://ajaxref.com/cgi-bin/upload.cgi?sid="
+ sid;
document.requestForm.onsubmit = function(){startProgressBar();};
};

This then toggles the interface and begins an Ajax request to monitor upload progress:

function startProgressBar()
{
document.getElementById("bar").style.display = "";
document.requestForm.uploadButton.disabled = true;
sendRequest();
}

Using the AjaxTCR library, a request is made to the server-side monitoring program.

function sendRequest()
{
var url = "http://ajaxref.com/ch8/progressmonitor.php";
var payload = "sid=" + sid;
var options = {method:"GET",
payload : payload,
onSuccess: handleResponse};
AjaxTCR.comm.sendRequest(url, options);
}

The JSON response contains the information necessary to alert the user to the progress
of the upload.

function handleResponse(response)
{
var data = AjaxTCR.data.decodeJSON(response.xhr.responseText);
var percent = data[0];
var statusSpan = document.getElementById("statusSpan");
var barStatus = document.getElementById("barStatus");
statusSpan.innerHTML = percent + "% Complete";
if (data[2] != 0 && data[1])
statusSpan.innerHTML += " - " + data[1] + " / " + data[2];
barStatus.style.width = percent + "%";
if (percent < 100)
setTimeout("sendRequest()", 500);
else
clearFileArray();
}
Free download pdf