Ajax Database in XML
? AJAX with Database using XML (Classic ASP Example)
This example demonstrates how to:
Use AJAX to request data.
Fetch that data from a database using Classic ASP.
Format the result as XML.
Return it to the browser and display it dynamically.
? Requirements
A database (e.g., MS Access or SQL Server)
An ASP file to query the database and return XML
An HTML/JavaScript file to call the ASP via AJAX
? 1?? Database Table Example
Table name: employees
Fields: id, name, position
| id | name | position |
|---|---|---|
| 1 | Vikash Gupta | Developer |
| 2 | Ravi Kumar | Designer |
? 2?? ASP File: get_employees.asp
<%Response.ContentType = "text/xml"Response.Write("<?xml version='1.0' encoding='UTF-8'?>")Response.Write("<employees>")Set conn = Server.CreateObject("ADODB.Connection")conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("db.mdb")sql = "SELECT name, position FROM employees"Set rs = conn.Execute(sql)Do Until rs.EOF Response.Write("<employee>") Response.Write("<name>" & Server.HTMLEncode(rs("name")) & "</name>") Response.Write("<position>" & Server.HTMLEncode(rs("position")) & "</position>") Response.Write("</employee>") rs.MoveNextLooprs.Closeconn.CloseSet rs = NothingSet conn = NothingResponse.Write("</employees>")%>?
Server.HTMLEncode()is used to safely encode special characters.
? 3?? HTML + AJAX File: index.html
<!DOCTYPE html><html><head> <title>AJAX Database XML Example</title></head><body><h2>Employee List (Loaded from DB via AJAX + XML)</h2><div id="output"></div><script>function loadData() { const xhttp = new XMLHttpRequest(); xhttp.onload = function () { const xml = this.responseXML; const employees = xml.getElementsByTagName("employee"); let output = "<ul>"; for (let i = 0; i < employees.length; i++) { const name = employees[i].getElementsByTagName("name")[0].textContent; const position = employees[i].getElementsByTagName("position")[0].textContent; output += `<li>${name} - ${position}</li>`; } output += "</ul>"; document.getElementById("output").innerHTML = output; }; xhttp.open("GET", "get_employees.asp", true); xhttp.send();}// Load on page loadwindow.onload = loadData;</script></body></html>? Result
When the page loads,
AJAXsends a request toget_employees.asp.The ASP page queries the database and returns XML.
JavaScript reads that XML and displays the results on the web page.
?? Notes
For larger databases, consider filtering with query parameters like
get_employees.asp?dept=HR.For production, use JSON instead of XML for lighter, faster performance.
This works with MS Access or SQL Server (change connection string accordingly).
Would you like an example using:
Search/filter via AJAX?
Inserting data to DB via AJAX?
The same example using JSON instead of XML?
Let me know!