Making Ajax Requests with YUI

Exclusive offer: get 50% off this eBook here
Yahoo User Interface Library 2.x Cookbook

Yahoo User Interface Library 2.x Cookbook — Save 50%

Over 70 simple incredibly effective recipes for taking control of Yahoo! User Interface Library like a Pro

$26.99    $13.50
by Matt Snider | January 2011 | AJAX Open Source Web Development

The Yahoo! User Interface (YUI) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML, and AJAX.

In this article by Cody Precord, author of the book Yahoo! User Interface Library 2.x Cookbook, we will cover:

  • Making your first AJAX request
  • Exploring the callback object properties
  • Exploring the response object properties
  • Using callback event functions

 

Yahoo! User Interface Library 2.x Cookbook

Yahoo! User Interface Library 2.x Cookbook

Over 70 simple incredibly effective recipes for taking control of Yahoo! User Interface Library like a Pro

 
  • Easily develop feature-rich internet applications to interact with the user using various built-in components of YUI library
  • Simple and powerful recipes explaining how to use and implement YUI 2.x components
  • Gain a thorough understanding of the YUI tools
  • Plenty of example code to help you improve your coding and productivity with the YUI Library
  • Hands-on solutions that takes a practical approach to recipes
        Read more about this book      

(For more resources on Yui, see here.)

Introduction

In this article, you will learn the YUI way of making Asynchronous JavaScript and XML (AJAX) requests. Although, all modern browsers support sending asynchronous requests to the server, not all browsers work the same way. Additionally, you are not required to return XML; your AJAX requests may return JSON, text, or some other format if you prefer. The Connection component provides a simple, cross-browser safe way to send and retrieve information from the server.

Making your first AJAX request

This recipe will show you how to make a simple AJAX request using YUI.

Getting ready

To use the Connection component, you must include the YUI object, the Event component, and the core of the Connection component:

<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="pathToBuild/yahoo/yahoo-min.js"
type="text/javascript"></script>
<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="pathToBuild/event/event-min.js"
type="text/javascript"></script>
<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="pathToBuild/connection/connection_core-min.js"
type="text/javascript"></script>

If you plan on using the form serialization example, or other advanced features, you will need to include the whole component, instead of only the core features:

<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="pathToBuild/connection/connection-min.js"
type="text/javascript"></script>

How to do it...

Make an asynchronous GET request:

var url = "/myUrl.php?param1=asdf&param2=1234";
var myCallback = {
success: function(o) {/* success handler code */},
failure: function(o) {/* failure handler code */},
/* ... */
};
var transaction =
YAHOO.util.Connect.asyncRequest('GET', url, myCallback);

Make an asynchronous POST request:

var url = "/myUrl.php";
var params = "param1=asdf&param2=1234";
var myCallback = {
success: function(o) {/* success handler code */},
failure: function(o) {/* failure handler code */},
/* ... */
};
var transaction = YAHOO.util.Connect.asyncRequest(
'POST', url, myCallback, params);

Make an asynchronous POST request using a form element to generate the post data:

var url = "/myUrl.php";
var myCallback = {
success: function(o) {/* success handler code */},
failure: function(o) {/* failure handler code */},
/* ... */
};
YAHOO.util.Connect.setForm('myFormEelementId');
var transaction =
YAHOO.util.Connect.asyncRequest('POST', url, myCallback);

How it works...

All modern browsers have supported AJAX natively since the early 2000. However, IE implemented a proprietary version using the ActiveXObject object , while other browsers implemented the standard compliant XMLHttpRequest (XHR) object . Each object has its own implementation and quirks, which YUI silently handles for you. Both objects make an HTTP request to the provided URL, passing any parameters you specified. The server should handle AJAX requests like any normal URL request.

When making a GET request , the parameters should be added to the URL directly (as in the example above). When making a POST request, the parameters should be a serialized form string (&key=value pairs) and provided as the fourth argument. Connection Manager also allows you to provide the parameters for a GET request as the fourth argument, if you prefer.

Using the setForm function attaches a form element for serialization with the next call to the asyncRequest function . The element must be a form element or it will throw an exception.

YUI polls the browser XHR object until a response is detected, then it examines the response code and the response data to see if it is valid. If it is valid, the success event fires, and if it is not, the failure event fires. YUI wraps the XHR response with its own connection object, thereby masking browser variations, and passes the wrapper object as the first argument of all the AJAX callback functions.

There's more...

Beside POST and GET, you may also use PUT, HEAD, and DELETE requests, but these may not be supported by all browsers or servers.

It is possible to send synchronous request through the native XHR objects, however Connection Manager does not support this.

The asyncRequest function returns an object known as the transaction object . This is the same object that YUI uses internally to manage the XHR request. It has the following properties:

See also

Exploring the callback object properties recipe, to learn what properties you can set on the callback object.

Exploring the response object recipe, to learn what properties are available on the YUI object passed into your callback functions.

Exploring the callback object properties

The third argument you can provide to the asyncRequest function defines your callback functions and other related response/request properties. This recipe explains what those properties are and how to use them.

How to do it...

The properties available on the callback object are:

var callback = {
argument: {/* ... */},
abort: function(o) {/* ... */},
cache: false,
failure: function(o) {/* ... */},
scope: {/* ... */},
success: function(o) {/* ... */},
timeout: 10000, // 10 seconds
upload: function(o) {/* ... */},
};

How it works...

The various callback functions attached to the connection object use the CustomEvent.FLAT callback function signature. This way the response object is the first argument of the callback functions. Each of the callback functions is subscribed to the appropriate custom event by the asyncRequest function. When the Connection Manager component detects the corresponding event conditions, it fires the related custom event.

The upload callback function is special because an iframe is used to make this request. Consequently, YUI cannot reasonably discern success or failure, nor can it determine the HTTP headers. This callback will be executed both when an upload is successful and when it fails, instead of the success and failure callback functions.

The argument property is stored on the response object and passed through to the callback functions. You can set the argument to anything that evaluates as true.

When the cache property is true, YUI maps the responses to the URLs, so if the same URL is requested a second time, Connection Manager can simply execute the proper callback function immediately.

The timeout property uses the native browser setTimeout function to call the abort function when the timeout expires. The timeout is cleared when an AJAX response is detected for a transaction.

See also

Exploring the response object properties recipe, to learn what properties are available on the YUI object passed into your callback functions.

Using event callback functions recipe, to learn common practices for handling failure and success callback functions.

Yahoo User Interface Library 2.x Cookbook Over 70 simple incredibly effective recipes for taking control of Yahoo! User Interface Library like a Pro
Published: January 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on Yui, see here.)

Exploring the response object properties

The YUI response object is passed as the first argument of all the callback functions. This recipe explains what properties are available on the object and how to use them.

How to do it...

The response object for normal AJAX request responses is:

var o = {
tId: 1234,
status: 201,
statusText: 'OK',
getResponseHeader: { /* ... */ },
getAllResponseHeaders: "ResponseHeadersAsAString",
responseText: "<xml>Hello World</xml>",
responseXML: { /* an XML document */ },
argument: { /* ... */ }
};

The response object for a failed response due to a non-responding HTTP request is:

var o = {
tId: 1234,
status: 0,
statusText: 'communication failure',
argument: { /* ... */ }
};

The response object for an aborted request is:

var o = {
tId: 1234,
status: -1,
statusText: 'transaction aborted',
argument: { /* ... */ }
};

The response object for a cross-domain response is:

var o = {
tId: 1234,
responseText: "<xml>Hello World</xml>",
argument: { /* ... */ }
};

The response object for an upload response is:

var o = {
tId: 1234,
responseText: "<p>Upload Successful</p>",
responseXML: { /* an XML document */ },
argument: { /* ... */ }
};

How it works...

All connection objects contain the transaction ID (tId) property, as defined by YUI, and the argument property you provided in the callback object. In all cases, except the upload callback, there will be a status and statusText property to help you understand what happened to the request. The server will respond with a code somewhere in the 200s if successful, and anything else is usually an error.

For the upload and success callbacks, the response object will contain responseText and responseXML. The responseText is the textual representation of the response, which may be text, JSON data, or XML. The responseXML is an XML document that is only set if the response header returned by the server is set to "text/xml" (set to the iframe document when using upload, if it can be handled like XML).

There's more...

If you are interested in the response headers, they are available on the response object passed to the success function , except when making cross-domain requests, which are not able to parse as much information. Additionally, successful cross-domain requests do not have a responseXML property , even if the returned response type is "text/xml". These are the limitations of the technology used to make cross-domain requests.

To fetch all the headers as a string, use the getAllResponseHeaders property . If you want to fetch a particular header, YUI has already parsed the string for you, and you can reference that header by name on the getResponseHeader object . Although every server is different, here is an example response header object which you may find useful:

var responseHeader = {
"Cache-Control": "must-revalidate",
Connection: "Keep-Alive",
"Content-Encoding": "gzip",
"Content-Language": "en-US",
"Content-Length": "191",
"Content-Type": "text/xml;charset=UTF-8"
Date: "Sun, 28 Feb 2010 19:13:39 GMT",
Expires: "0",
Pragma: "no-cache",
Server: "Apache-Coyote/1.1",
Vary: "Accept-Encoding, User-Agent"
};

Handling event callback functions

This recipe shows some of the common ways you might use the success and failure callback functions.

How to do it...

Handle a successful GET request that returns a textual response, and inserts that response directly into the DOM:

var url = "/getNode.php?param1=asdf&param2=1234";
var processResponse = function(text, obj) {
YAHOO.util.Dom.get('myElementId').innerHTML = text;
};
var callback = {
success: function(o) {
if (o.responseText) {
processResponse(o.responseText, o.argument);
}
else {
alert("Error: response is missing");
}
}
};
var transaction =
YAHOO.util.Connect.asyncRequest('GET', url, callback);

A successful GET request of an XML document returns an XML response, such as:

<auto>
<year>2009</year>
<make>Honda</make>
<model>Accord</model>
</auto>

Handle parsing values out of the XML response:

var url = "/getAuto.php?id=1234";
var processResponse = function(xml, obj) {
var year =
xml.getElementsByTagName('year')[0].firstChild.nodeValue;
var model =
xml.getElementsByTagName('model')[0].firstChild.nodeValue;
var make =
xml.getElementsByTagName('make')[0].firstChild.nodeValue;
alert(year + ' ' + make + ' ' + model);
};
var callback = {
success: function(o) {
if (o.responseXML) {
processResponse(o.responseXML, o.argument);
}
else if (o.responseText) {
alert("Error:response Content-Type is not text/XML");
}
else {
alert("Error: response is missing");
}
}
};
var transaction =
YAHOO.util.Connect.asyncRequest('GET', url, callback);

Here is an example JSON response:

<?php
header('Content-type: text/json');
echo '{"year":2009,"make":"Honda","model":"Accord"}';
?>

Handle a successful POST request that returns the above JSON response:

var processResponse = function(json, obj) {
var year = json.year;
var model = json.model;
var make = json.make;
};
var callback = {
success: function(o) {
if (o.responseText) {
try {
var json = YAHOO.lang.JSON.parse(o.responseText);
processResponse(json, o.argument);
}
catch(e) {
alert("Error: response is unparsable");
}
}
else {
alert("Error: response is missing");
}
}
};
var transaction = YAHOO.util.Connect.asyncRequest('POST',
"/getJSON.php", callback, "id=1234&type=auto");

Handle a failed POST request:

var callback = {
argument: "/../getJSON.php?id=1234&type=auto",
failure: function(o) {
alert("Error: request failed for " + o.argument +
", status="+o.status+", statusText="+o.statusText);
}
};
var transaction = YAHOO.util.Connect.asyncRequest('POST',
"/../getJSON.php", callback, "id=1234&type=auto");

How it works...

These functions show some basic ways to handle the request callback functions. For success functions, you should generally evaluate the callback against the desired data, and then forward that data to another function for processing. Failure functions should log or alert you to the issue at hand.

Summary

This article taught us how to:

  • make AJAX requests with YUI
  • Explore the callback and response object properties and
  • Use callback event functions.

Further resources on this subject:


Yahoo User Interface Library 2.x Cookbook Over 70 simple incredibly effective recipes for taking control of Yahoo! User Interface Library like a Pro
Published: January 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Matt Snider

Matt Snider is a software engineer and JavaScript enthusiast. He has built various web applications from the ground up, since 2003, but has maintained a passion for the UI. He quickly discovered YUI because of its early adoption, great documentation, and strong open-source community. Matt currently maintains a blog dedicated to web application development, leads the UI team at http://www.mint.com, and authored the YUI 2.x Storage Component. In the near future, he plans to port the Storage component to YUI 3. Examples of his work can be found on his personal website http://www.mattsnider.com.

Books From Packt


PHP jQuery Cookbook
PHP jQuery Cookbook

Learning Ext JS 3.2
Learning Ext JS 3.2

Python Geo-Spatial Development
Python Geo-Spatial Development

PostgreSQL 9.0 High Performance
PostgreSQL 9.0 High Performance

Drupal 7 First Look
Drupal 7 First Look

YUI 2.8: Learning the Library
YUI 2.8: Learning the Library

Inkscape 0.48 Essentials for Web Designers
Inkscape 0.48 Essentials for Web Designers

Joomla! 1.5 Cookbook
Joomla! 1.5 Cookbook


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software