Suscriber with us



Receive HTML?

Syndicate

AJAX Database PDF Print E-mail

AJAX can be used for interactive communication with a database.

AJAX Database Example

In the AJAX example below we will show how a web page can fetch information from a MySQL database using AJAX technology.


User info will be listed here.

This example consists of four elements:

  1. a MySQL database
  2. a simple HTML form
  3. a JavaScript
  4. a PHP page
  5. The Database
  6. The database we will be using in this example looks like this:

id

FirstName

LastName

Age

Hometown

Job

 1
 

Peter

Griffin

41

Quahog

Brewery

2

Lois

Griffin

40

Newport

PianoTeacher
 

3
 

Joseph

Swanson

39

Quahog

PoliceOfficer

4
 

Glenn

Quagmire

41

Quahog

Pilot

The HTML Form

The example above contains a simple HTML form and a link to a JavaScript:

<html><head>
<script src="selectuser.js"></script>
</head>
<body>
<form>
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>
</body></html>

Example Explained - The HTML Form

As you can see it is just a simple HTML form with a drop down box called "users" with names and the "id" from the database as option values.

The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.

When the user selects data, a function called "showUser()" is executed. The execution of the function is triggered by the "onchange" event.

In other words: Each time the user changes the value in the drop down box, the function showUser() is called.

The JavaScript

This is the JavaScript code stored in the file "selectuser.js":

var xmlHttp
function showUser(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="getuser.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
 }
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}



Last Updated ( Thursday, 03 April 2008 )
 
< Prev   Next >

Polls

Which is the best Scripting language?