Latest web development tutorials

AJAX Database

AJAX can be used for interactive communication with the database.


AJAX database instance

The following examples will demonstrate how a web page via AJAX read information from the database:

Examples


Customer info will be listed here...


Examples explain - HTML page

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

<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
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 info will be listed here...</div>

</body>
</html>

Source explained:

If you do not select a customer (str.length == 0), then the function will clear txtHint placeholder, and then exit the function.

If you have selected a customer, then showCustomer () function performs the following steps:

  • Create XMLHttpRequest object
  • Create function when the server is ready to perform the response
  • File on the server to send requests
  • Please note added to the end of the URL parameter (q) (contains the contents of the drop-down list)

ASP file

The above servers through JavaScript calling this page is called "getcustomer.asp" ASP files.

"Getcustomer.asp" source code 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("<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>")
%>