AJAX lets a web page send an HTTP request to a server-side ASP endpoint and update part of the page without a full navigation. Classic ASP can return plain text, HTML fragments, or structured data; the browser-side request is made with JavaScript.
Older AJAX tutorials commonly build an XMLHttpRequest object and include Internet Explorer ActiveXObject fallbacks. Modern browsers provide the promise-based fetch() API, which is usually simpler for new front-end code. XMLHttpRequest still exists and may be encountered in legacy applications.
<%
Response.ContentType = "text/plain"
Response.Write "Hello World"
%><script>
async function sendRequest(event) {
event.preventDefault();
const output = document.getElementById("txtReturn");
try {
const response = await fetch("post.asp", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ source: "ajax-demo" })
});
if (!response.ok) throw new Error("HTTP " + response.status);
output.textContent = await response.text();
} catch (error) {
output.textContent = "Request failed.";
}
}
</script>
URLSearchParams correctly encodes name/value pairs for an application/x-www-form-urlencoded request. The code also checks response.ok; a Fetch promise does not automatically reject just because the server returns an HTTP error status.
<form id="ajaxForm" onsubmit="sendRequest(event)">
<button type="submit">Send request</button>
</form>
<div id="txtReturn" aria-live="polite">Return message will appear here.</div>
When a response is plain text, assign it with textContent instead of innerHTML unless you intentionally return trusted HTML and have handled the associated injection risk.
The original two-file AJAX package remains available for learners maintaining older XMLHttpRequest-based code: download the legacy AJAX example ZIP.
<%
Response.ContentType = "text/plain"
Dim source
source = Trim(Request.Form("source"))
If source = "ajax-demo" Then
Response.Write "Hello World"
Else
Response.Status = "400 Bad Request"
Response.Write "Invalid source"
End If
%>Save this as post.asp for the Fetch example. A real application also checks the HTTP method, request authenticity and any data being submitted.
Validate every request on the ASP endpoint even if the browser uses fetch(). Place untrusted plain-text results in textContent rather than innerHTML, and add CSRF protection to state-changing requests.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.