Table of Contents
Key Takeaways
A Simple HTTP Request Example
The Problem
The Simple Example Revisited
Our Project: The WebConsole Application
A Little Extra
Working with XML
Using jQuery
Using YUI
Conclusion
Frequently Asked Questions about AJAX
What is the difference between synchronous and asynchronous AJAX?
How does AJAX handle data formats like XML and JSON?
Can AJAX work with technologies other than JavaScript?
What are the security implications of using AJAX?
How does AJAX affect SEO?
Can AJAX be used with HTML5 and CSS3?
What are some common use cases for AJAX?
How does AJAX handle errors?
Can AJAX requests be cached?
How can I debug AJAX?
Home Web Front-end JS Tutorial Take Command with Ajax

Take Command with Ajax

Mar 06, 2025 am 01:03 AM

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:


  1. Create an XMLHttpRequest object.

  2. Assign a callback function to handle the HTTP response.

  3. 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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Here’s how this example works:


  1. The user clicks the “Make a request” button.

  2. 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.

  3. The request is sent.

  4. The onreadystatechange event fires and the execution is passed to alertContents().

  5. 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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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>
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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>
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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

that contains the results of the commands executed so far, and one where we type the commands to be executed. They both have a black background and gray courier font. Here’s a screenshot.

Take Command with Ajax

The HTML

Here’s the HTML part of the application:

var callmeback = alert;<br>
callmeback('test'); // alerts 'test'
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

That’s it: a

that gets updated with the results of the command being executed, and an into which we can type commands. It’s a nice, clean interface, with no

The above is the detailed content of Take Command with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles