5 min read

In this Ajax tutorial, 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.

How to make 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=”pathToBuild/yahoo/yahoo-min.js”
type=”text/javascript”></script>
<script src=”pathToBuild/event/event-min.js”
type=”text/javascript”></script>
<script src=”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=”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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here