goog.net.XhrIo: make simple ajax calls with Google Closure

Closure has a consistent package called goog.net, which contains a lot of classes to work with ajax and remote http requests. In this post I want to show how to create a basic xhr object to make get/post calls, listen for related ajax events and send data to server. Once imported the main js file (base.js), we will require the following:

goog.require('goog.dom');
goog.require('goog.net.XhrIo');
goog.require('goog.structs.Map');
goog.require('goog.Uri.QueryData');

The most important import is goog.net.XhrIo, which represents the object wrapping the XmlHttpRequest and allows us to retrieve and send information to/from the server. This class is a pretty low level api, which means that several tasks are not as simple and automatic as they would in jQuery or such libraries, but on the other hand this offers us more control and consciousness of what we are going to do.
The first step is instantiate an object of type goog.net.XhrIo and take a reference to it:

var request = new goog.net.XhrIo();

Then we will be able to listen for events:

goog.events.listen(request, 'complete', ajaxCallBack);

In this case we will listen to a “complete” event, which is an event always dispatched by goog.net.XhrIo even if the call fails. We can however listen to a “success”, an “error”, an “abort” or a “readystatechange” event, but in most cases listen only to “complete” is the best and easy choice. If we decide to listen to “complete” event, we will handle the result and ask to goog.net.XhrIo if the ajax call has been successful or not:

goog.events.listen(request, 'complete', function(){
					
    if (request.isSuccess()) {
			
        // do something cool			
						
    } else {
		
        // display an apologize message				
					
    }
					
});

To start the request we will use the send() method, which accepts the following parameters: the url to call (the only mandatory argument), the method to use (usually “GET” or “POST”), a query string containing the parameters to send and a map (key-value object) representing custom headers to send.
Before starting the ajax call, let’s see how to create an object that will holds data to send to the server by using the class goog.Uri.QueryData:

var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
    title: 'Test ajax data',
    content: 'foo',
    param1: 2500
}));

As I can see from Closure reference, the approach above is the faster way to create a “data container” in order to send data with ajax. We can use the static method createFromMap() of goog.Uri.QueryData and pass an anonymous map (which has no reference) to it. A map is one of the several objects coming from the Java world that has been introduced in Closure by Google under the package goog.structs, it is essentially an object containing a certain number of keys holding a determinate value. Once we have our data stored into a goog.Uri.QueryData we will use the toString() method to send it through ajax, send() method in fact expects a string representation of the data (param1=value&param2=value…) not an object:

request.send('ajax-test.jsp', 'POST', data.toString());

The complete example’s code is the following:

goog.require('goog.dom');
goog.require('goog.net.XhrIo');
goog.require('goog.structs.Map');
goog.require('goog.Uri.QueryData');
			
function doRequest() {
				
    // create the xhr object
    var request = new goog.net.XhrIo();
				
    // create a QueryData object by initializing it with a simple Map
    var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
        title: 'Test ajax data',
        content: 'foo',
        param1: 2500
    }));
				
    // listen to complete event
    goog.events.listen(request, 'complete', function(){
					
        if (request.isSuccess()) {
						
            // inject response into the dom
            goog.dom.$('response').innerHTML = request.getResponseText();
						
            // print confirm to the console
            console.log('Satus code: ', request.getStatus(), ' - ', request.getStatusText());
						
        } else {
						
            // print error info to the console
            console.log(
                'Something went wrong in the ajax call. Error code: ', request.getLastErrorCode(),
                ' - message: ', request.getLastError()
            );
						
        }
					
    });
				
    // start the request by setting POST method and passing
    // the data object converted to a queryString
    request.send('ajax-test.jsp', 'POST', data.toString());
				
}
  • Lennox

    Thanks!

  • This was extremely helpful, thank you

  • Ben

    Thanks, really helped me

  • Peter

    thanks