Frontend Development 15 min read

Understanding AJAX: Principles, Form Submission, XMLHttpRequest, jQuery Implementation, Advantages and Disadvantages

This article explains the fundamentals of AJAX, including its definition, the need for asynchronous communication, how form submissions work, the XMLHttpRequest object methods and properties, jQuery implementations, advantages, disadvantages, and typical application and non‑application scenarios, with complete code examples.

Wukong Talks Architecture
Wukong Talks Architecture
Wukong Talks Architecture
Understanding AJAX: Principles, Form Submission, XMLHttpRequest, jQuery Implementation, Advantages and Disadvantages

Table of Contents

What is AJAX

Principle of Form Submission

Principle of Request and Response

XMLHttpRequest Object

jQuery AJAX Implementation

Advantages

Disadvantages

Application Scenarios

Non‑Applicable Scenarios

Background

Traditional web pages reload the entire page when a form is submitted.

If the server takes a long time to respond, the client appears unresponsive.

After the server returns a response, the browser must reload the whole page, increasing load.

Form submission sends a large amount of data, affecting network performance.

Problems

How to improve the situation?

What is AJAX?

What are its advantages?

What are its disadvantages?

1. What is AJAX?

Why AJAX is needed

When data must be fetched from the server and the page refreshed, without AJAX the whole form must be submitted, causing the page to wait for the server response before the user can continue.

AJAX definition

AJAX = Asynchronous JavaScript and XML.

It is a technique for creating fast, dynamic web pages.

By exchanging a small amount of data with the server in the background, the page can be updated asynchronously.

It allows updating parts of a page without reloading the entire page.

What is asynchronous?

The current page sends a request to the server and does not need to wait for the response before the user continues interacting with the page.

What is partial refresh?

Two ways to achieve partial refresh:

Using an <iframe> (page reload inside the iframe, which still has performance drawbacks).

Using JavaScript to change the src of the iframe and reload only its content.

Example of iframe method:

<iframe id="indexFrame" name="index" width="1000" height="800" frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="margin-top:100px;"></iframe>
var indexFrame = document.getElementById("indexFrame");
indexFrame.src = "introduction.php";
<button id="room" onclick='IndexClick("room")'>Click Me!</button>
function IndexClick(moduleKey) {
    var indexFrame = document.getElementById("indexFrame");
    if (indexFrame == null) {
        indexFrame = parent.document.getElementById("indexFrame");
    }
    var url = "introduction.php";
    switch (moduleKey) {
        case "introduction":
            url = "introduction.php";
            break;
        case "room":
            url = "room.php";
            break;
        default:
            {}
    }
    indexFrame.src = url;
}

This technique can be used to build a navigation bar where only the iframe content changes.

2. AJAX request flow

JavaScript sends an asynchronous request.

The server queries the database and returns data.

The server sends a response.

The client processes the response and updates the DOM.

Example: when a DropDownList item changes, JavaScript sends an AJAX request, receives data, builds a table, and inserts it into the page.

3. Form submission principle

Client HTML:

<form id="form1" action="Test.ashx" method="get">
    您的姓名1:<input type="text" name="fname" size="20" />
    <input type="submit" name="submit" value="Sumbit">
</form>

Server C# handler (simplified):

public void ProcessRequest(HttpContext context) {
    for (int i = 0; i < 2; i++) {
        System.Threading.Thread.Sleep(1000);
    }
    string fname = context.Request["fname"];
    context.Response.ContentType = "text/plain";
    context.Response.Write("Hello World " + fname);
}

After deploying to IIS and opening http://localhost:8003/Test.html , entering a name and clicking Submit, the page refreshes and displays "Hello World <name>".

4. AJAX request and response principle (full example)

Client HTML:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript" src="Ajax.js"></script>
</head>
<body>
    <div id="Test" style="background-color:#40eeee">
        您的姓名2:<input type="text" id="testGetName" size="20" />
        <button type="button" onclick="testGet();">Ajax Get请求</button>
    </div>
    <div id="Test" style="background-color:#ff6a00">
        您的姓名3:<input type="text" id="testPostName" size="20" />
        <button type="button" onclick="testPost();">Ajax Post请求</button>
    </div>
    <div id="myDiv" />
</body>
</html>

Client JavaScript (Ajax.js):

var xmlhttp = createRequest();
function testGet() {
    var fname = document.getElementById("testGetName").value;
    xmlhttp.open("GET", "Test.ashx?fname=" + fname + "&random=" + Math.random(), true);
    xmlhttp.onreadystatechange = callback;
    xmlhttp.send(null);
}
function testPost() {
    var fname = document.getElementById("testPostName").value;
    xmlhttp.open("POST", "Test.ashx?&random=" + Math.random(), true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    xmlhttp.onreadystatechange = callback;
    xmlhttp.send("fname=" + fname);
}
function createRequest() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;
}
function callback() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
}

Note: The request object should be global only if you handle a single request at a time; otherwise create separate objects to avoid callback conflicts.

5. XMLHttpRequest object

Methods and properties are illustrated with images in the original source (e.g., open, send, setRequestHeader, readyState, status, responseText, etc.).

6. jQuery AJAX implementation

function getWeeklyCalendar(name, currentDate, mode) {
    $.ajax({
        type: 'POST',
        url: 'weekProcess.php',
        data: 'func=getWeeklyCalender&name=' + name + '&currentDate=' + currentDate + '&mode=' + mode,
        success: function(data) {
            paintWeeklyCandler(data);
        }
    });
}

Server PHP returns JSON data which is then processed by paintWeeklyCandler(data) .

Advantages

Asynchronous communication eliminates page reloads.

Data is fetched on demand, reducing server load.

Web applications respond more quickly to user interactions.

Based on widely supported standards; no plugins required.

Separation of concerns: JavaScript handles UI, server handles logic and data.

Disadvantages

Security concerns: exposing server methods can be attacked.

Large amount of JavaScript code can be error‑prone.

Users may be confused by invisible page updates.

Can interfere with browser back‑button behavior.

Some mobile browsers have limited AJAX support.

Application Scenarios

Filtering and manipulating data on the client side.

Adding/removing tree nodes.

Adding/removing rows in a table.

Switching dropdown items.

Username availability checks during registration.

Non‑Applicable Scenarios

Saving the entire page content.

Full‑page navigation.

© 悟空聊架构 – Follow for daily progress tips and free books.

JavaScriptasynchronousweb developmentAjaxjQueryXMLHttpRequest
Wukong Talks Architecture
Written by

Wukong Talks Architecture

Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.