Take Command with Ajax
Do you want to build more dynamic, responsive, desktop-like web applications like Gmail and Google Maps? Then this article is for you! It guides you through the Ajax basics and through the process of building a simple Ajax application.
That application is named WebConsole, a browser interface for executing system commands for which you’d usually need shell access. There are also short examples of using the Ajax functionality of two popular JavaScript libraries – jQuery and YUI.
In this article, first published in 2005 and recently updated, I’ll explain the creation of one simple, reusable JavaScript function for making HTTP requests. Then, I’ll apply that function in the creation of a simple application.
Although there are some YUI and jQuery examples, the article is not a tutorial on a specific Ajax library. Instead, it aims to give you more hands-on information about making HTTP requests, so that you’re in a better position when evaluating such libraries or deciding to go on your own.
Key Takeaways
- Ajax allows for the creation of dynamic, responsive web applications similar to Gmail and Google Maps by handling HTTP requests within the browser.
- The tutorial introduces a reusable JavaScript function for making HTTP requests, which can be used across various applications without relying on specific libraries like jQuery or YUI.
- A simple example demonstrates the basic steps of making an HTTP request: creating an XMLHttpRequest object, assigning a callback function, and sending the request.
- The article introduces the WebConsole application, enabling server-side command execution through a browser interface, illustrating practical Ajax use.
- Security concerns are highlighted, emphasizing the importance of restricting executable commands and sanitizing inputs to prevent unauthorized server access.
- The tutorial covers advanced topics, including handling different data formats like XML and JSON, and integrating Ajax with popular JavaScript libraries for enhanced functionality.
A Simple HTTP Request Example
Let’s first revise the flow of making an HTTP request in JavaScript, and handling the response. This is just a quick example to refresh your memory. For all the spicy details, see SitePoint’s introductory article, “Ajax: Usable Interactivity with Remote Scripting.”
There are three basic steps:
- Create an XMLHttpRequest object.
- Assign a callback function to handle the HTTP response.
- Make (send) the request.
Let’s see an example where we’ll request a simple HTML document, test.html, which only contains the text “I’m a test.” We’ll then alert() the contents of the test.html file:
<button >Make a request</button> <br> <br> <script type="text/javascript"> <br> <br> var http_request = false; <br> <br> function makeRequest(url) { <br> <br> if (window.XMLHttpRequest) { // Mozilla, Safari, IE7... <br> http_request = new XMLHttpRequest(); <br> } else if (window.ActiveXObject) { // IE6 and older <br> http_request = new ActiveXObject("Microsoft.XMLHTTP"); <br> } <br> http_request.onreadystatechange = alertContents; <br> http_request.open('GET', url, true); <br> http_request.send(null); <br> <br> } <br> <br> function alertContents() { <br> if (http_request.readyState == 4) { <br> if (http_request.status == 200) { <br> alert(http_request.responseText); <br> } else { <br> alert('There was a problem with the request.'); <br> } <br> } <br> } <br> <br> document.getElementById('mybutton').onclick = function() { <br> makeRequest('test.html'); <br> } <br> <br> </script>
Here’s how this example works:
- The user clicks the “Make a request” button.
- This calls the makeRequest() function with a parameter: the name of an HTML file in the same directory. In this case, it’s test.html.
- The request is sent.
- The onreadystatechange event fires and the execution is passed to alertContents().
- alertContents() checks if the response was received and, if it’s okay, then alert()s the contents of the test.html file.
Test the example for yourself, and view the test file.
The Problem
The above example worked just fine, but there’s one thing we need to improve before we’re ready for prime time. The improvement is to code a reusable request function that handles all the boring and repetitive object creation and request/response stuff, while leaving the presentational part to other functions, which are request-agnostic and deal with the result only, regardless of its source.
In the example above, we needed a global variable, http_request, that was accessible by both the makeRequest() and alertContents() functions, which is not good in terms of reusability and also risks naming collisions. Ideally, makeRequest() should perform the request and alertContents() should just present the result; neither function needs know about or require the other.
Here’s the code for our reusable request function:
<button >Make a request</button> <br> <br> <script type="text/javascript"> <br> <br> var http_request = false; <br> <br> function makeRequest(url) { <br> <br> if (window.XMLHttpRequest) { // Mozilla, Safari, IE7... <br> http_request = new XMLHttpRequest(); <br> } else if (window.ActiveXObject) { // IE6 and older <br> http_request = new ActiveXObject("Microsoft.XMLHTTP"); <br> } <br> http_request.onreadystatechange = alertContents; <br> http_request.open('GET', url, true); <br> http_request.send(null); <br> <br> } <br> <br> function alertContents() { <br> if (http_request.readyState == 4) { <br> if (http_request.status == 200) { <br> alert(http_request.responseText); <br> } else { <br> alert('There was a problem with the request.'); <br> } <br> } <br> } <br> <br> document.getElementById('mybutton').onclick = function() { <br> makeRequest('test.html'); <br> } <br> <br> </script>
This function receives three parameters:
- the URL to get
- the function to call when the response is received
- a flag if the callback function expects an XML document (true) or plain text (false, default)
This function relies on two JavaScript capabilities in order to wrap and isolate the request object nicely. The first is the ability to define new functions (called anonymous functions) on the fly, like this:
http_request.onreadystatechange = function() {...}
The other trick is the ability to invoke callback functions without knowing their names in advance; for example:
function makeHttpRequest(url, callback_function, return_xml) <br> { <br> var http_request, response, i; <br> <br> var activex_ids = [ <br> 'MSXML2.XMLHTTP.3.0', <br> 'MSXML2.XMLHTTP', <br> 'Microsoft.XMLHTTP' <br> ]; <br> <br> if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+... <br> http_request = new XMLHttpRequest(); <br> if (http_request.overrideMimeType) { <br> http_request.overrideMimeType('text/xml'); <br> } <br> } else if (window.ActiveXObject) { // IE6 and older <br> for (i = 0; i < activex_ids.length; i++) { <br> try { <br> http_request = new ActiveXObject(activex_ids[i]); <br> } catch (e) {} <br> } <br> } <br> <br> if (!http_request) { <br> alert('Unfortunately your browser doesn't support this feature.'); <br> return false; <br> } <br> <br> http_request.onreadystatechange = function() { <br> if (http_request.readyState !== 4) { <br> // not ready yet <br> return; <br> } <br> if (http_request.status !== 200) { <br> // ready, but not OK <br> alert('There was a problem with the request.(Code: ' + http_request.status + ')'); <br> return; <br> } <br> if (return_xml) { <br> response = http_request.responseXML; <br> } else { <br> response = http_request.responseText; <br> } <br> // invoke the callback <br> callback_function(response); <br> }; <br> <br> http_request.open('GET', url, true); <br> http_request.send(null); <br> }
Note how the name of the callback function is passed without any quotes.
You can easily make the function even more reusable by allowing the HTTP request method as well as any query string to be passed as parameters to the function and then used in calls to open() and send() methods. This will also allow you to make POST requests in addition to the GETs it was originally intended to perform.
Another capability of the function is the handling of response codes other than 200, which could be handy if you want to be more specific and take appropriate actions depending on the type of the success/error code returned.
The Simple Example Revisited
Now let’s redo the previous example in which the contents of a test.html file were alert()ed. This time, by employing our shiny new reusable request function, the revised versions of the two functions used will be much simpler:
<button >Make a request</button> <br> <br> <script type="text/javascript"> <br> <br> var http_request = false; <br> <br> function makeRequest(url) { <br> <br> if (window.XMLHttpRequest) { // Mozilla, Safari, IE7... <br> http_request = new XMLHttpRequest(); <br> } else if (window.ActiveXObject) { // IE6 and older <br> http_request = new ActiveXObject("Microsoft.XMLHTTP"); <br> } <br> http_request.onreadystatechange = alertContents; <br> http_request.open('GET', url, true); <br> http_request.send(null); <br> <br> } <br> <br> function alertContents() { <br> if (http_request.readyState == 4) { <br> if (http_request.status == 200) { <br> alert(http_request.responseText); <br> } else { <br> alert('There was a problem with the request.'); <br> } <br> } <br> } <br> <br> document.getElementById('mybutton').onclick = function() { <br> makeRequest('test.html'); <br> } <br> <br> </script>
As you can see, alertContents() is simply presentational: there are no states, readyStates, or HTTP requests flying around whatsoever.
Since these functions are now just one-liners, we can in fact get rid of them entirely, and change the function call instead. So the whole example will become:
function makeHttpRequest(url, callback_function, return_xml) <br> { <br> var http_request, response, i; <br> <br> var activex_ids = [ <br> 'MSXML2.XMLHTTP.3.0', <br> 'MSXML2.XMLHTTP', <br> 'Microsoft.XMLHTTP' <br> ]; <br> <br> if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+... <br> http_request = new XMLHttpRequest(); <br> if (http_request.overrideMimeType) { <br> http_request.overrideMimeType('text/xml'); <br> } <br> } else if (window.ActiveXObject) { // IE6 and older <br> for (i = 0; i < activex_ids.length; i++) { <br> try { <br> http_request = new ActiveXObject(activex_ids[i]); <br> } catch (e) {} <br> } <br> } <br> <br> if (!http_request) { <br> alert('Unfortunately your browser doesn't support this feature.'); <br> return false; <br> } <br> <br> http_request.onreadystatechange = function() { <br> if (http_request.readyState !== 4) { <br> // not ready yet <br> return; <br> } <br> if (http_request.status !== 200) { <br> // ready, but not OK <br> alert('There was a problem with the request.(Code: ' + http_request.status + ')'); <br> return; <br> } <br> if (return_xml) { <br> response = http_request.responseXML; <br> } else { <br> response = http_request.responseText; <br> } <br> // invoke the callback <br> callback_function(response); <br> }; <br> <br> http_request.open('GET', url, true); <br> http_request.send(null); <br> }
Yes, it’s that easy! View the example and full source code (available through our old friend View Source).
Our Project: The WebConsole Application
Knowing the Ajax basics, and armed with a reusable way of making requests, let’s go deeper, to create a little something that can actually be used in real life.
The application we’ll create will allow you to execute any shell command on your web server, whether it’s Windows- or Linux-based. We’ll even put in a little CSS effort in an attempt to make the app feel more like a console window.
Interface-wise, we have one scrollable
The HTML
Here’s the HTML part of the application:
var callmeback = alert;<br> callmeback('test'); // alerts 'test'
That’s it: a
The above is the detailed content of Take Command with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
