AJAX Database Example
- Previous Page AJAX ASP
- Next Page AJAX Application
AJAX can be used for interactive communication with the database.
AJAX Database Example
The following examples demonstrate: how web pages can read information from a database using AJAX:
Example
Example explanation - showCustomer() function
When the user selects a customer from the dropdown list above, the function named "showCustomer()" is executed. This function is onchange
Event trigger:
showCustomer
function showCustomer(str) { var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "getcustomer.asp?q=" + str, true); xhttp.send(); }
The showCustomer() function performs the following:
- Check if a customer is selected
- Create an XMLHttpRequest object
- Create a function to be executed when the server response is ready
- Send a request to a file on the server
- Please note that the parameter q is added to the URL (with content in a dropdown list)
AJAX server page
The server page called by the above JavaScript is an ASP file named "getcustomer.asp".
It is easy to rewrite the server file using PHP or other server-side languages.
See the corresponding PHP example.
The source code in "getcustomer.asp" runs a database query and 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("customers.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>") next rs.MoveNext loop response.write("</table>") %>
- Previous Page AJAX ASP
- Next Page AJAX Application