WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

AJAX Database Example


AJAX can be utilized for intelligent correspondence with a database.


AJAX Database Example

The following precedent will show how a site page can get data from a database with AJAX:

Example


Customer information will be recorded here...


Example Explained - The HTML Page

When a client chooses a client in the dropdown list over, a capacity called "showCustomer()" is executed. The work is activated by the "onchange" event:

<!DOCTYPE html>
<html>
<head>
<script>
work showCustomer(str)
{
in the event that (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
in the event that (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 information will be recorded here...</div>

</body>
</html>

Source code explanation:

If no client is chosen (str.length==0), the capacity clears the substance of the txtHint placeholder and ways out the function.

If a client is chosen, the showCustomer() work executes the following:

  • Create a XMLHttpRequest object
  • Create the capacity to be executed when the server reaction is ready
  • Send the demand off to a document on the server
  • Notice that a parameter (q) is added to the URL (with the substance of the dropdown list)

The ASP File

The page on the server called by the JavaScript above is an ASP document called "getcustomer.asp".

The source code in "getcustomer.asp" runs a question against a database, and returns the outcome in a 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("/datafolder/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn

response.write("<table>")
do until rs.EOF
  for every 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>")
%>