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 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 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!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),