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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1255
29
C# Tutorial
1228
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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 Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

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: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

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 vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

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.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

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.

See all articles