Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript does not use jQuery's Ajax requests


May 09, 2021 CoffeeScript


Table of contents


Ajax requests that do not use jQuery

Problem

You want to load data from your server through AJAX instead of using the jQuery library.

Solution

You will use the local XMLHttpRequest object.

Open 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 we click the button, we want to send an Ajax request to the server to get some data. For this example, we use a JSON small file.

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

Then, create a CoffeeScript file to save the page logic. The code in this file creates a function that is 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

Discuss

In the above code, we processed the keys in HTML (line 16) and added a click event listener (line 17). In the event listener, we define the callback function as the loadDataFromServer.

We defined the beginning of the loadData FromServer callback on line 2.

We created an XMLHttpRequest request object (line 3) and added a readystatechange event processor. The moment the requested ReadyState changes, it is triggered.

In the event processor, we check to see if the readyState is satisfied, which, if equal to, indicates that the request has been completed. T hen check the status value of the request. A status value of 200 or 304 indicates a successful request, while others indicate an error.

If the request does succeed, we will recalculate the JSON returned from the server and assign it to a data variable. At this point, we can use the returned data when we need it.

At the end of the day we need to make a request.

On line 13, a "GET" request is opened to read the data.json file.

Send our request to the server on line 14.

Legacy server support

If your app needs to use an older version of Internet Explorer, you need to make sure that the XMLHttpRequest object exists. To do this, you can enter the following code before creating an 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 that the XMLHttpRequest object is available in the global namespace.