Use of AJAX in PHP with database

AJAX is about updating parts of the Web page, without reloading the entire page and update page. We use AJAX to show data on the same window. For example we select the name in the text and fetch all data in a table and all the records are shown in the same window through AJAX.

1. Create HTML page

When a user selects a Name in the dropdown list, a function called "showUser()" is executed. The function is triggered by the "onchange" event:

<html>

<head>

<script>

function showUser(str) {

if (str == "") {

document.getElementById("txtHint").innerHTML = "";

return;

}

if (window.XMLHttpRequest)

{

xmlhttp = new XMLHttpRequest();

}

else {

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange = function () {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

document.getElementById("txtHint").innerHTML = xmlhttp.responseText;

}

}

xmlhttp.open("GET", "ajax2.php?q=" + str, true);

xmlhttp.send();

}

</script>

</head>

<body>

<form>

<select name="users" onChange="showUser(this.value)">//onchange is a Html Event

<option value="">Select a person:</option>

<option value="1">vinod Kumar</option>

<option value="2">Sharad gupta</option>

<option value="3">ram Kumar</option>

<option value="4">alok Kumar</option>

</select>

</form>

<br>

<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>

</html>

The showUser() function does the following:

2. Create PHP page

The page on the server called by the JavaScript above is a PHP file called "ajax2.php".

The source code in "ajax2.php" runs a query against a MySQL database, and returns the result in an HTML table:

<html>

<head>

<title>Untitled Document</title>

</head>

<body>

<?php

$q=$_GET["q"];

$con = mysql_connect('localhost','root', '');

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

mysql_select_db("ajax", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$res = mysql_query($sql);

echo "<table border='1'>

<tr>

<th>Firstname</th>

<th>Lastname</th>

<th>Age</th>

</tr>";

while($row = mysql_fetch_array($res))

{

echo "<tr>";

echo "<td>" . $row['First name'] . "</td>";

echo "<td>" . $row['Last name'] . "</td>";

echo "<td>" . $row['Age'] . "</td>";

echo "</tr>";

}

echo "</table>";

mysql_close($con);

?>

</body>

</html>

Explanation

When the query is sent from the JavaScript to the PHP file, the following happens:

  1. PHP opens a connection to a MySQL server.
  2. The correct Name is found.
  3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder.

Output

ajax1-in-php.jpg

ajax2-in-php.jpg

ajax3-in-php.jpg