The XMLHttpRequest object is used to send and receive data between a web browser and web server. Up to now, we have been retrieving data from data sources that remain relatively static, such as text or XML files.

In this tutorial, we will learn how to use the same Ajax concepts that we have learned so far and pull data from your database. We will be using an ASP file to handle the server-side scripting and MySQL as our database.

You can replace ASP with any other server-side scripting language that you are familiar with such as PHP, or ASP.NET. The back-end data source can be swapped for MS Access, as well as MSSQL. The concept remains the same.

HTML Example

Select an Employee for more details!

ASP Example

<% Response.AddHeader “Cache-Control”, “no-cache” %> <% Response.AddHeader “Cache-Control”, “no-store” %> <% Response.AddHeader “Cache-Control”, “must-revalidate” %> <% Response.AddHeader “Pragma”, “no-cache” %> <% Response.AddHeader “Expires”, “Sat, 14 Jan 2012 01:00:00 GMT” %> <% Dim oConn, oRs Dim qry, cstr Dim db_name, db_username, db_userpassword Dim db_server

db_server = “dbserver.com” db_name = “databaseName” db_username = “dbUserName” db_userpwd = “dbPassword” tablename = “employees” fieldname1 = “empName” fieldname2 = “empTitle” fieldname3 = “empOffice” q = request.querystring(“q”)

cstr = “Driver={MySQL ODBC 3.51 Driver};SERVER=” & db_server & “;DATABASE=” & db_name & “;UID=” & db_username & “;PWD=” & db_userpwd

Set oConn = Server.CreateObject(“ADODB.Connection”) oConn.Open cstr

qry = “SELECT * FROM " & tablename & " WHERE empID = " & q

Set oRS = oConn.Execute(qry) response.write("

”) if not oRS.EOF then while not oRS.EOF response.write ("”) response.write ("”) response.write ("”) oRS.movenext wend oRS.close end if response.write("
Name:" & oRs.Fields(fieldname1) & “
Title:" & oRs.Fields(fieldname2) & “
Office:" & oRs.Fields(fieldname3) & “
") Set oRs = nothing Set oConn = nothing %>