AJAX can be used to dynamically communicate with the database.
The following example will demonstrate how a web page reads information from the database via AJAX: Please select a customer in the drop-down list below:
When the user selects a customer in the drop-down list above, a function named "showCustomer()" is executed. This function is triggered by the "onchange" event:
function showCustomer ( str ) { var xmlhttp ; if ( str == " " ) { document . getElementById ( " txtHint " ) . innerHTML = " " ; return ; } if ( window . XMLHttpRequest ) { // IE7+, Firefox, Chrome, Opera, Safari browser execution code xmlhttp = new XMLHttpRequest ( ) ; } else { // IE6, IE5 browser execution 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 " , " /try/ajax/getcustomer.php?q= " + str , true ) ; xmlhttp . send ( ) ; }The showCustomer() function performs the following tasks:
Check if a customer has been selected
Create XMLHttpRequest object
Execute the created function when the server response is ready
Send the request to a file on the server
Note that we added a parameter q to the URL (with the contents of the input field)
The server page called by the above JavaScript is a PHP file named "getcustomer.php".
It's also easy to write server files in PHP, or other server languages. See the corresponding example written in PHP.
The source code in "getcustomer.php" is responsible for querying the database and returning the results in an HTML table:
<%response.expires=-1sql="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,connresponse.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.MoveNextloopresponse.write("</table>")%>