Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

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.

File#1

<?php include(“connect.inc”);
$db = public_db_connect();
?>
<html>
<head>
<script type=”text/javascript”>
function listMembers(str)
{
if (str==””)
{
document.getElementById(“my_text”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“my_text”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”ajax-get-input.php?formname=”+str,true);
xmlhttp.send();
//alert(str);
}

</script>
</head>

<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)) {

$id=$row[‘id’];
$firstname=$row[‘firstname’];
echo ‘<div id=”my_text”><input type=”button” value=”‘.$firstname.'” name=”‘.$id.'” onclick=”listMembers(this.name)” /></div>’;
}
}?>
</form>
</html>

File #2

<?php include(“connect.inc”);
$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)){
$first_name=$row[‘firstname’];
echo “Output for: “.$first_name.”<br/>”;
echo ‘<input type=”text” value=”‘.$first_name.'” name=”members” />’;
}

mysqli_close($db);
?>