AJAX Database Example

AJAX can be used for bidirectional communication with databases.

AJAX Database Example

The following example demonstrates how a web page can read information from a database using AJAX:

Customer information will be listed here.

Try the source code yourself

Example Explanation - HTML Page

When a user selects a customer from the drop-down list above, the function named "showCustomer()" will be executed. This function is triggered by the "onchange" event:

<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  // For IE7+, Firefox, Chrome, Opera, Safari code
  xmlhttp=new XMLHttpRequest();
  }
else
  // For IE6, IE5 code
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getcustomer.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head
<body>
<form>
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer information will be listed here...</div>
</body>
</html>

Source code explanation:

If no customer has been selected (str.length is equal to 0), the function will clear the txtHint placeholder and then exit the function.

If a customer has been selected, the showCustomer() function will perform the following steps:

  • Create an XMLHttpRequest object
  • Create a function to be executed when the server response is ready
  • Send a request to the file on the server
  • Please note the parameter (q) added to the end of the URL (including the content of the dropdown list)

ASP file

The server page called by this JavaScript is an ASP file named "getcustomer.asp".

"The source code in "getcustomer.asp" will run a query against the database and then return 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("<table>")
do until rs.EOF
  for each x in rs.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rs.MoveNext
loop
response.write("</table>")
%>