XMLHttpRequest Level 1 and 2: Communicating with the Server
This tutorial demonstrates how you can communicate with a Web server using HTTP requests.
Warm-up
Become familiar with the XMLHttpRequest Level 1 and 2 API basics by learning about:
-
Sending a Cross-origin Request
Send a cross-domain request to the Web server.
-
Uploading Files with Ajax
Upload files on the background using Ajax.
-
Handling Request Events
Track requests through various events.
-
Tracking Download Progress State
Start and cancel a download and track the download status.
Sending a Cross-origin Request
To use the XML HTTP request features in your application, you must learn to send a cross-origin request:
-
Create an XMLHttpRequest interface instance:
<script> var client = new XMLHttpRequest();
-
Open the connection with the open() method using the cross-domain URL as a parameter. Send the request with the send() method.
client.open("GET", "video_sample.mp4"); client.send(); </script>
Note Cross-domain access only works if the server allows the domain access of the client.
Source Code
For the complete source code related to this use case, see the following files:
Uploading Files with Ajax
To use the XML HTTP request features in your application, you must learn to upload files on the background with Ajax:
-
Define the input elements for the file upload. Use the upload() method for the button click event to upload the file when the button is clicked.
<input type="file" id="uploadfile" name="uploadfile" /> <input type="button" value="upload" onclick="upload()" />
-
In the upload() method, create a FormData interface instance, and add the file element with the attached file into it. Use the send() method to send the FormData to the server.
<script> var client = new XMLHttpRequest(); function upload() { var file = document.getElementById("uploadfile"); /* Create a FormData instance */ var formData = new FormData(); /* Add the file */ formData.append("upload", file.files[0]); client.open("post", "/upload", true); client.setRequestHeader("Content-Type", "multipart/form-data"); client.send(formData); /* Send to server */ } /* Check the response status */ client.onreadystatechange = function() { if (client.readyState == 4 && client.status == 200) { alert(client.statusText); } } </script>
Source Code
For the complete source code related to this use case, see the following file:
Handling Request Events
To use the XML HTTP request features in your application, you must learn to track requests through events:
-
Define a text element in which to display the request event results:
<div id="divText"></div>
-
Create an XMLHttpRequest interface instance and define event handlers for it:
<script> var html = ""; var client = new XMLHttpRequest(); /* Event handlers */ client.onloadstart = onloadstarthandler; client.onprogress = onprogresshandler; client.onabort = onaborthandler; client.onerror = onerrorhandler; client.onload = onloadhandler; client.ontimeout = ontimeouthandler; client.onloadend = onloadendhandler; client.onreadystatechange = onreadystatechangehandler; /* Assign request type and server path */ client.open("GET", "video_sample.mp4"); client.send();
-
Define the actions of each event handler:
/* When the request begins */ function onloadstarthandler(e) { html += "onloadstart<br/>"; document.getElementById("divText").innerHTML = html; } /* When the request is in progress */ function onprogresshandler(e) { html += "onprogress<br/>"; document.getElementById("divText").innerHTML = html; } /* When the client cancels the request */ function onaborthandler(e) { html += "onabort<br/>"; document.getElementById("divText").innerHTML = html; } /* When server exception occurs */ function onerrorhandler(e) { html += "onerror<br/>"; document.getElementById("divText").innerHTML = html; } /* When the request is successfully terminated */ function onloadhandler(e) { html += "onload<br/>"; document.getElementById("divText").innerHTML = html; } /* When a timeout occurs */ function ontimeouthandler(e) { html += "ontimeout<br/>"; document.getElementById("divText").innerHTML = html; } /* When request is terminated regardless of success or failure */ function onloadendhandler(e) { html += "onloadend<br/>"; document.getElementById("divText").innerHTML = html; } /* Checks current progress based on a random repetition period */ function onreadystatechangehandler(e) { html += "onreadystate<br/>"; document.getElementById("divText").innerHTML = html; } </script>
Source Code
For the complete source code related to this use case, see the following files:
Tracking Download Progress State
To use the XML HTTP request features in your application, you must learn to track download progress:
-
Define the input elements for managing a download. Use the sendRequest() and abortRequest() methods for the button click events to start and cancel a download.
<input type="button" value="Send XMLHttpRequest" onclick="sendRequest()" /> <input type="button" value="Abort Sending" onclick="abortRequest()" /> <div id="divText"></div>
-
Create an XMLHttpRequest interface instance and define the handlers for the onprogress and onabort events to track the download progress and cancellation events:
<script> var client = new XMLHttpRequest(); client.onprogress = onprogresshandler; client.onabort = onaborthandler; </script>
-
Use the send() method to request for a file to be read when the Start download button is clicked. When the Cancel download button is clicked, use the abort() method to cancel the download.
<script> /* When Start download button is clicked */ function sendRequest() { client.send(); } /* When Cancel download button is clicked */ function abortRequest() { client.abort(); }
-
During the download, use the onprogresshandler event handler to track the current and total download size, and calculate the download status. With the onaborthandler event handler, you can display the cancellation notification on the screen.
function onprogresshandler(e) { document.getElementById("divText").innerHTML = "DownLoading.. (" + parseInt(e.loaded / e.totalSize * 100) + "%)"; } function onaborthandler(e) { document.getElementById("divText").innerHTML = "Download has been cancelled by user."; } </script>
Source Code
For the complete source code related to this use case, see the following file: