Latest web development tutorials

AJAX Database

AJAX can be used to dynamically communicate with the database.


AJAX database instance

The following example will demonstrate how a web page via AJAX to read information from the database: Please select a client in the following drop-down list:

Example


Customer info will be listed here...

try it"


Examples explain - showCustomer () function

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

function showCustomer(str)
{
var xmlhttp;
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.html?q="+str,true);
xmlhttp.send();
}

showCustomer () function performs the following tasks:

  • Check that you have selected a customer
  • Create XMLHttpRequest object
  • Create function executed when the server response is ready
  • Send the request to a file on the server
  • Please note that we have added a parameter q (with the content of the input field) to the URL

AJAX server page

Server page called by the JavaScript above is a PHP file named "getcustomer.php".

Written in PHP server files easily, or other server language. See the corresponding example written in PHP .

"Getcustomer.php" source code responsible for the database query, then returns the results in HTML form:

<%
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>")
%>