5.2 XMLHttpRequest (AJAX)

One of the most frequently used asynchronous APIs in the development of applications with TypeScript is the XMLHttpRequest API, which can be used to retrieve data from the server without reloading the page being displayed in the web browser.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher and jQuery.

How to do it

The following code snippet can be used to request some JSON data asynchronously:

const async = true;
const url = '/my/url';
const request = new XMLHttpRequest();
request.open('GET', url, async);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error
  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

How it works

The preceding code snippet declares three variables. The first variable is used as a configuration parameter in the AJAX request. The second variable is used to store a reference to the resource URL and the third variable is used to store a reference to the request object.

The code snippet also declares two event handlers for the onload and onerror events. The onload event handler checks the requests status and transform the response (text) into JSON if there have been no server side errors.

There’s more

Many libraries like JQuery wrap the XMLHttpRequest API to provide cross-browser support and a cleaner coding style. For example, the following code snippet performs a request identical to the one performed by the preceding code snippet using the jQuery AJAX API:

const async = true;
const url = '/my/url';

$.ajax({
  url: url,
  async : async,
  method: "GET",
  dataType : "json",
  success: function(data) {
  	// Success!
  },
  error : function() {
  	// There was a connection error of some sort
  }
}); 

Source Code

XMLHttpRequest (AJAX)
XMLHttpRequest (AJAX JQery)

See also

Please refer to the recipes about callbacks and promises in this chapter to learn about more about the XMLHttpRequest API.


Shiv Kushwaha

Author/Programmer