PHP tutorial- AJAX

PHP tutorial- AJAX


Using PHP with AJAX

In this tutorial, you learn to use AJAX with PHP. AJAX is a good mechanism that allows to write JavaScript code to interact with web server. By using AJAX, you can get data from server and update content of a web page without reloading the page. For an example in this tutorial, we are going to create a product page. On this web page, the user is able to view products by category. There is a category drop down list. By selecting a category from the drop down list, a list of products in that category will display right below the drop down list. The categories and products information are retrieved from the stockdb MySQL database. There are two tables that must be created on your MySQL database server: tblproduct and tblcategory. The tblproduct has three columns: id, name, and catid. The tblcategory table has three columns: id, name, and description. In one category, there are many products and one product is only in a category.

PHP and AJAX to get data from server

Now you will need to create a class to connect and read data from the stockdb database. Here is the content of the datahandler.php file that contain the DataHandler class. The DataHandler class will connect to the database when its object is created. You need to supply the host name, user, password, and database name to its constructor. The getProducts method will be called to read the products' information from tblproduct table by category. The getCategories method is called to display all categories in the drop down list. The closeConnection can be called to close the connection with MySQL databaser server.

<?php


class DataHandler{
private $con;
private $db;

public function DataHandler($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME){


  $this->con=mysql_connect($DB_HOST,$DB_USER,$DB_PASS) or die(mysql_error());

  if (!$this->con) {
   echo "Unable to connect to DB: " . mysql_error();
   exit;
}
$this->db=mysql_select_db($DB_NAME,$this->con);
if (!$this->db) {
  echo "Unable to select mydbname: " . mysql_error();
  exit;
 }
}

public function getProducts($tblname,$cat){

  if($cat!=="")
   $query="SELECT * FROM ".$tblname." WHERE catid='$cat'";
  else
   $query="SELECT * FROM ".$tblname;

  $result=mysql_query($query);
  $numrows=mysql_num_rows($result);
  $str="";
  if($numrows>0) {

   $str="<table >";
   $str.="<tr style='background-color:#dfdfdf'><th>ID</th><th>Name</th><th>Category</th></tr>";
   while($datarow=mysql_fetch_row($result)){
    $str.="<tr>"."<td>".$datarow[0]."</td>"."<td>".$datarow[1]."</td>"."<td>".$datarow[2]."</td></tr>";
  }
  $str.="</table>";
}
else
  $str.="<p style='color:#ff1111'>No products to display</p>";
  return $str;

}

public function getCategories($tblname){
  $query="SELECT * FROM ".$tblname;
  $result=mysql_query($query);
  $str="";
  while($datarow=mysql_fetch_row($result)){
   $str.="<option value='$datarow[0]'>".$datarow[1]."</option><br/>";
  }
  return $str;
 }


public function closeConnection(){
  mysql_close($this->con);
 }

}

?>

Below is the content of the productpage.php file. It is the products web page that allows the user to view products by category.

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Products Page</title>
<script>

function listproducts(str)
{
if (str.length==0)
{
return;
}
//create ajax request object
var xmlhttp=new XMLHttpRequest();
//get the response text from server
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;

}
}
//send the request to server asynchronously
xmlhttp.open("GET","getproducts.php?catid="+str,true);
xmlhttp.send();
}
</script>
</head>

<body onload="listproducts(1)">
<?php
  //Include database handler file
  //This file contains the DataHandler class that has methods to connect and get records
  //from database.
  include("./datahandler.php");
?>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="dropcat"></label>
<select name="dropcat" id="dropcat" onchange="listproducts(this.value)" style="width:300px">
<?php
  //connect to the stockdb database and retrieve data from tblcategory table to populate drop down list
  $DataH=new DataHandler("localhost","test","test","stockdb");
  $str=$DataH->getCategories("tblcategory");
  $DataH->closeConnection();
   echo $str;
?>
</select>
</p>
<p>&nbsp;</p>
</form>
<div id="results" style="width:300px"></div>
</body>
</html>

The AJAX request object sends the request to server by specifying the getproducts.php file on server that will handle the request when the page loads and each time the user selects a category from the drop down list. The request sent to the server contains a category of products. The result string that is the response text from server is displayed in a div tag right below the drop down list. The response text contains the list of products in that category. Below is the content of the getproducts.php file.

<?php
  include("./datahandler.php"); //include DataHandler class to handle connection and data retrieval
  $cat=$_REQUEST['catid']; //get category sent by AJAX from productpage page
  $DataH=new DataHandler("localhost","test","test","stockdb"); //create DataHandler object
  echo $DataH->getProducts("tblproduct",$cat); //return selected products
  $DataH->closeConnection(); //close connection
?>

 


Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.