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