We will continue with our
AJAX Tutorials and make small
AJAX Application using
AJAX PHP MySQL Query to edit data in
MySQL Database.
Lets say we have some
MySQL table with employs and we have to list their names in drop-down <select> menu and when we select someone from the list, personal data will be displayed in table where we can edit the data.
First we have to make HTML page where the drop-down list will be generated from
MySQL Database by
PHP server side and also we have to place some
<div></div> tags where will display employs data.
Lets give name '
index.php' for this file.
Now some explanations. Between <select onchange="display_data(this.value);"> and </select> we generate entire list with employs names by PHP MySQL query.
Now we have to put some handler which can handle change event on <select> drop down list and to call function display_data() with parameter this.value - selected value from drop down list on change event. this function return personal details for this employ and this data later will be formatted in table placed in <div id="employ_data"></div> tags.
Now lets update our index.php file with included AJAX function - display_data().
Like you see
display_data() AJAX function uses server side
PHP script for getting the employs data. In this
PHP script we have using
MySQL Query to return the data to
AJAX script.
Next, when we successfully receive the data from
PHP server side script we have to place this data formated in table in
<div id="employ_data"></div> tags.
Now lets update our index.php file including the new
display_data() AJAX function which now will place returned data
PHP script in right place:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function display_data(id) {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null) {
alert ("Your browser does not support AJAX!");
return;
}
var url="ajax.php";
url=url+"?employ_id="+id;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete") {
document.getElementById('employ_data').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
</script>
</head>
<body>
<select onchange="display_data(this.value);">
<option>Select employ</option>
<?php
mysql_connect('localhost','user','pass');
mysql_select_db('employ');
$query="select id, name from employ order by name asc";
$result=mysql_query($query);
while(list($id, $name)=mysql_fetch_row($result)) {
echo "<option value=\"".$id."\">".$name."</option>";
}
?>
</select>
<div id="employ_data"></div>
</body>
</html>
Now let see how our
AJAX Application works. Please select some employ from drop-down list below.
posted on 2009-Jun-16 | 08:07:47 PM
posted on 2009-Jun-26 | 03:20:11 PM