óCoffeeScript Cookbook

Ajax Request Without jQuery

Problem

You want to load data from your server via AJAX without using the jQuery library.

Solution

You will use the native XMLHttpRequest object.

Let's set up a simple test HTML page with a button.

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>XMLHttpRequest Tester</title>
</head>
<body>
    <h1>XMLHttpRequest Tester</h1>
    <button id="loadDataButton">Load Data</button>
    
    <script type="text/javascript" src="XMLHttpRequest.js"></script>
</body>
</html>

When the button is clicked, we want to send an Ajax request to the server to retrieve some data. For this sample, we have a small JSON file.

// data.json
{
  message: "Hello World"
}

Next, create the CoffeeScript file to hold the page logic. The code in this file creates a function to be called when the Load Data button is clicked.

 1 # XMLHttpRequest.coffee
 2 loadDataFromServer = ->
 3   req = new XMLHttpRequest()
 4 
 5   req.addEventListener 'readystatechange', ->
 6     if req.readyState is 4                        # ReadyState Complete
 7       successResultCodes = [200, 304]
 8       if req.status in successResultCodes
 9         data = eval '(' + req.responseText + ')'
10         console.log 'data message: ', data.message
11       else
12         console.log 'Error loading data...'
13         
14   req.open 'GET', 'data.json', false
15   req.send()
16 
17 loadDataButton = document.getElementById 'loadDataButton'
18 loadDataButton.addEventListener 'click', loadDataFromServer, false

Discussion

In the above code we essentially grab a handle to the button in our HTML (line 16) and add a click event listener (line 17). In our event listener, we define our callback function as loadDataFromServer.

We define our loadDataFromServer callback beginning on line 2.

We create a XMLHttpRequest request object (line 3) and add a readystatechange event handler. This fires whenever the request's readyState changes.

In the event handler we check to see if the readyState = 4, indicating the request has completed. Then, we check the request status value. Both 200 or 304 represent a successful request. Anything else represents an error condition.

If the request was indeed successful, we eval the JSON returned from the server and assign it to a data variable. At this point, we can use the returned data in any way we need to.

The last thing we need to do is actually make our request.

Line 13 opens a 'GET' request to retrieve the data.json file.

Line 14 sends our request to the server.

Older Browser Support

If your application needs to target older versions of Internet Explorer, you will need to ensure the XMLHttpRequest object exists. You can do this by including this code before creating the XMLHttpRequest instance.

if (typeof @XMLHttpRequest == "undefined")
  console.log 'XMLHttpRequest is undefined'
  @XMLHttpRequest = ->
    try
      return new ActiveXObject("Msxml2.XMLHTTP.6.0")
    catch error
    try
      return new ActiveXObject("Msxml2.XMLHTTP.3.0")
    catch error
    try
      return new ActiveXObject("Microsoft.XMLHTTP")
    catch error
    throw new Error("This browser does not support XMLHttpRequest.")

This code ensures the XMLHttpRequest object is available in the global namespace.