AJAX Database Example
AJAX can be used to communicate interactively with a database.
AJAX Database Example
The example below demonstrates how a web page reads information from a database through AJAX:
Example
Customer info will be listed here...
Example Explanation - HTML Page
When the user selects a customer from the drop-down list above, a function named "showCustomer()" is executed. This function is triggered by the "onchange" event:
Source code explanation:
If no customer is selected (str.length==0), then the function clears the txtHint placeholder and exits the function.
If a customer is selected, the showCustomer() function performs the following steps:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send a request to the file on the server
- Note the parameter (q) appended to the end of the URL (containing the dropdown list contents)
ASP file
The server page called by JavaScript above is an ASP file named "getcustomer.asp".
The source code in "getcustomer.asp" runs a query against the database and then returns the results in an HTML table:
<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn
response.write("
do until rs.EOF
for each x in rs.Fields
response.write("
response.write("
next
rs.MoveNext
loop
response.write("
| " & x.name & " | ")" & x.value & " |
%>