AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 209


is quite easy, though it should be noted that the upload callback is a bit different than the
standard case because an XHR is not being used. The tId and argument properties will be
available in the callback. responseText and responseXML will also be available, though
these will correspond to any text or parsable XML found in the iframe after the file is posted.
No status values or management of the upload using methods like abort() will be possible.
The following example shows a basic use of YUI for handling a file upload:

<!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 5 : YUI - File Upload</title>
<script src="http://yui.yahooapis.com/2.3.0/build/yahoo/yahoo-min.js"
type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.3.0/build/event/event-min.js"
type="text/javascript"></script>
<script src="http://yui.yahooapis.com/2.3.0/build/connection/connection-min.js"
type="text/javascript"></script>
<script type="text/javascript">
function doUpload()
{
var uploadForm = document.getElementById("uploadform");
var callback = { upload: function(o){ alert(o.responseText);} };
YAHOO.util.Connect.setForm(uploadForm,true);
var request = YAHOO.util.Connect.asyncRequest("POST",
"http://ajaxref.com/ch4/upload/fileupload1.php", callback);
}
YAHOO.util.Event.addListener("uploadBtn", "click", doUpload);
</script>
</head>
<body>
<form id="uploadform">
<label> File: <input name="uploadedfile" type="file" /></label>
<input type="button" id="uploadBtn" value="Upload" />
</form>
</body>
</html>

The previous example can be found at http://ajaxref.com/ch5/yuiupload.html.

YUI Connection Handling Details
The YUI library provides a number of useful methods to handle connections, though clearly,
directly manipulating XHRs allows even more flexibility. For example, in the YUI version
used for this book (2.3.0) there is no direct way to perform a synchronous request. However,
any gaps may be filled by the time you read this, so check the online documentation for the
library just to be sure YUI doesn’t support something not discussed here.
Header control in YUI is performed automatically in the case of setting the right
Content-Type values for POST and such, though this can be overridden by using the
setDefaultPostHeader() method:

YAHOO.util.Connect.setDefaultPostHeader(false);
Free download pdf