- Challenges of the AJAX User Interface
- Processing Major Transactions
- Marking Changed Content
- Summary
Processing Major Transactions
At times in every AJAX application, the user simply has to stop playing with the interactive elements and wait for the application to complete. Perhaps the AJAX application is saving critical data or performing a financial transaction that shouldn’t be interrupted, or the application may be starting a series of loads that should be completed before the user is allowed to take control.
In both cases, you could use synchronous XMLHttpRequest mode, which effectively blocks the browser—that is, the browser is unresponsive while executing JavaScript—but has these significant shortcomings (apart from being unfriendly toward the user):
- The transaction cannot be aborted following a timeout. The only means of aborting the HTTP request is to wait until the server completes the request or terminates the TCP session.
- The browser window is completely frozen; it might even appear as a hung program to the Windows Task Manager.
- The user has no means of interrupting the transaction.
Alternatively, you could open a modal dialog box when the web request is started, giving the user an option to cancel the transaction. Obviously, the dialog box would be closed automatically when the web request completes. The modal dialog box should be opened after the web request has been sent with the send method of the XMLHttpRequest object, and closed automatically when the onreadystatechange handler is called with readyState property set to 4 (loading complete). The following code listing shows a sample of this technique:
var xmlhttp; function ajax_dhtml_loadHandler() { if (xmlhttp.readyState == 4) { Modal.cancelMessageBox(); // perform other processing } } var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", sFromUrl, true); xmlhttp.onreadystatechange = ajax_dhtml_loadHandler; xmlhttp.send(""); Modal.messageBox( "Document is loading, cancel with <em>Esc</em>", "Please wait", Modal.CANCEL + Modal.LOADING,cancelGetContent);
The cancelGetContent callback function should abort the web request (it’s called only if the user clicks the Cancel button or presses the Esc key) and remove the onreadystatechange handler from the xmlhttp object to ensure that it’s never called. The implementation in the following listing displays another dialog box, informing the user that the request has been canceled:
function cancelGetContent() { xmlhttp.onreadystatechange = null; xmlhttp.abort(); Modal.messageBox( "Document loading has been cancelled", "Aborted", Modal.OK + Modal.WARNING); }
I’ve integrated the modal dialog box functionality into the AJAX library introduced in the "Introduction to HIJAX" article by adding a parameter to the getContentFromURI function. You can download the modified code from my web site or test the new Frequently Asked Question page in your browser.