AJAX with ASP

Connecting AJAX to ASP.NET backend

🌐 What is AJAX with ASP?

AJAX with ASP (Active Server Pages) enables dynamic interaction between web pages and Microsoft server technologies. You can send requests to ASP scripts, process data server-side, and update pages without reloading.


// Send request to ASP
xhr.open('GET', 'process.asp', true);
xhr.send();
                                    

AJAX + ASP Features

🗄️

Database Integration

Connect to SQL Server databases

Set conn = Server.CreateObject("ADODB.Connection")
⚙️

Server Processing

Execute VBScript or JScript code

Request.QueryString("name")
🔒

Session Management

Handle user sessions securely

Session("username")
📤

Dynamic Output

Generate HTML or JSON responses

Response.Write(data)

🔹 Simple ASP Script

ASP scripts process AJAX requests using VBScript or JScript. This basic example shows how ASP receives parameters and generates responses.

<%@ Language=VBScript %>
<%
' Simple ASP response script (response.asp)

' Get data from AJAX request
Dim name
name = Request.QueryString("name")

' Process and respond
If name <> "" Then
    Response.Write("Hello, " & name & "!")
Else
    Response.Write("Hello, Guest!")
End If
%>

ASP Output:

Hello, John!

🔹 AJAX GET Request to ASP

GET requests send data through URL parameters to ASP scripts. ASP retrieves these values using Request.QueryString and processes them server-side.

<!DOCTYPE html>
<html>
<body>

<h2>Get User Info</h2>
<input type="text" id="username" placeholder="Enter name">
<button onclick="getInfo()">Get Info</button>
<div id="result"></div>

<script>
function getInfo() {
    const name = document.getElementById('username').value;
    const xhr = new XMLHttpRequest();
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.getElementById('result').innerHTML = xhr.responseText;
        }
    };
    
    // Send GET request to ASP
    xhr.open('GET', 'getuser.asp?name=' + name, true);
    xhr.send();
}
</script>

</body>
</html>
<%@ Language=VBScript %>
<%
' getuser.asp
Dim name
name = Request.QueryString("name")

Response.Write("<h3>Welcome, " & Server.HTMLEncode(name) & "!</h3>")
Response.Write("<p>Your account is active.</p>")
%>

🔹 AJAX POST Request to ASP

POST requests send data in the request body for better security. ASP accesses POST data using Request.Form, making it ideal for form submissions.

<!DOCTYPE html>
<html>
<body>

<h2>User Registration</h2>
<input type="text" id="username" placeholder="Username">
<input type="email" id="email" placeholder="Email">
<button onclick="register()">Register</button>
<div id="message"></div>

<script>
function register() {
    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const xhr = new XMLHttpRequest();
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.getElementById('message').innerHTML = xhr.responseText;
        }
    };
    
    xhr.open('POST', 'register.asp', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    // Send POST data
    xhr.send('username=' + username + '&email=' + email);
}
</script>

</body>
</html>
<%@ Language=VBScript %>
<%
' register.asp
Dim username, email
username = Request.Form("username")
email = Request.Form("email")

' Validate data
If username = "" Or email = "" Then
    Response.Write("❌ Please fill all fields!")
Else
    ' Process registration (save to database, etc.)
    Response.Write("✅ Registration successful!")
    Response.Write("<br>Username: " & Server.HTMLEncode(username))
    Response.Write("<br>Email: " & Server.HTMLEncode(email))
End If
%>

🔹 ASP with Database

ASP commonly interacts with databases like SQL Server or Access. This example demonstrates querying a database and returning results to AJAX requests.

<%@ Language=VBScript %>
<%
' database.asp - Fetch from database
Dim conn, rs, sql, userId

' Get user ID from request
userId = Request.QueryString("id")

' Create database connection
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=server;Initial Catalog=database;User ID=user;Password=pass"

' Query database
sql = "SELECT id, name, email FROM users WHERE id = " & userId
Set rs = conn.Execute(sql)

' Check if record exists
If Not rs.EOF Then
    Response.Write("<h3>" & rs("name") & "</h3>")
    Response.Write("<p>Email: " & rs("email") & "</p>")
Else
    Response.Write("<p>User not found</p>")
End If

' Clean up
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
%>

Database Tips:

  • Use parameterized queries to prevent SQL injection
  • Close connections after use to free resources
  • Handle errors with On Error Resume Next
  • Encode output with Server.HTMLEncode()

🔹 ASP JSON Response

Modern applications use JSON for structured data exchange. ASP can generate JSON responses for easier parsing in JavaScript applications.

<%@ Language=VBScript %>
<%
' getuser.asp - Return JSON
Response.ContentType = "application/json"

Dim userId
userId = Request.QueryString("id")

' Simulate database query
' In real app, fetch from database

' Build JSON response
Dim json
json = "{"
json = json & """id"": " & userId & ","
json = json & """name"": ""John Doe"","
json = json & """email"": ""[email protected]"","
json = json & """age"": 30"
json = json & "}"

Response.Write(json)
%>
// JavaScript - Parse JSON from ASP
function loadUser() {
    const xhr = new XMLHttpRequest();
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            const user = JSON.parse(xhr.responseText);
            
            document.getElementById('output').innerHTML = 
                '<h3>' + user.name + '</h3>' +
                '<p>Email: ' + user.email + '</p>' +
                '<p>Age: ' + user.age + '</p>';
        }
    };
    
    xhr.open('GET', 'getuser.asp?id=1', true);
    xhr.send();
}

🔹 Complete AJAX-ASP Example

Here's a full working example showing a dropdown that loads data from ASP dynamically based on user selection:

<!DOCTYPE html>
<html>
<body>

<h2>Select Category</h2>
<select id="category" onchange="loadItems()">
    <option value="">Choose...</option>
    <option value="electronics">Electronics</option>
    <option value="books">Books</option>
    <option value="clothing">Clothing</option>
</select>
<div id="items"></div>

<script>
function loadItems() {
    const category = document.getElementById('category').value;
    
    if (category === '') {
        document.getElementById('items').innerHTML = '';
        return;
    }
    
    const xhr = new XMLHttpRequest();
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.getElementById('items').innerHTML = xhr.responseText;
        }
    };
    
    xhr.open('GET', 'getitems.asp?category=' + category, true);
    xhr.send();
}
</script>

</body>
</html>
<%@ Language=VBScript %>
<%
' getitems.asp
Dim category
category = Request.QueryString("category")

' Sample data (in real app, query database)
Response.Write("<h3>Items in " & Server.HTMLEncode(category) & ":</h3>")
Response.Write("<ul>")

Select Case LCase(category)
    Case "electronics"
        Response.Write("<li>Laptop</li>")
        Response.Write("<li>Smartphone</li>")
        Response.Write("<li>Tablet</li>")
    Case "books"
        Response.Write("<li>Fiction</li>")
        Response.Write("<li>Non-Fiction</li>")
        Response.Write("<li>Science</li>")
    Case "clothing"
        Response.Write("<li>Shirts</li>")
        Response.Write("<li>Pants</li>")
        Response.Write("<li>Shoes</li>")
End Select

Response.Write("</ul>")
%>

🧠 Test Your Knowledge

Which ASP object is used to get query string parameters?