PHP Ajax Example

PHP Ajax Example

The following example for php and ajax will show how to make an input box with a specific name when a button is clicked. When a button is clicked, the id for the particular person is passed into a url. The id of the person is then used to output his first name in an input box.

Three files are used. One file is the page you see in the browser, another file connects to the database and the third file outputs the new input box.


<?php include("");
$db = public_db_connect();
<script type="text/javascript">
function listMembers(str)
if (str=="")
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp.readyState==4 && xmlhttp.status==200)


<form method="post" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>"> <?php
$command= "SELECT id, firstname, lastname FROM table_sort WHERE id=3 ";
$result = mysqli_query($db, $command);
if ($result && mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {

echo '<div id="my_text"><input type="button" value="'.$firstname.'" name="'.$id.'" onclick="listMembers(" /></div>';

File #2

<?php include("");
$db = public_db_connect();
$myid = $_GET['formname'];
//echo $myid;

$command3="SELECT firstname, lastname FROM table_sort WHERE id ='$myid' ";
$result3 = mysqli_query($db, $command3);
while($row = mysqli_fetch_assoc($result3)){
echo "Output for: ".$first_name."<br/>";
echo '<input type="text" value="'.$first_name.'" name="members" />';