article

Saturday, August 17, 2013

Ajax, Php class dynamic select box

Ajax, Php class dynamic select box 

Create table state

CREATE TABLE IF NOT EXISTS `state` (
  `state_id` int(11) NOT NULL AUTO_INCREMENT,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(255) NOT NULL,
  PRIMARY KEY (`state_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 98, 'Zambales'),
(2, 98, 'Pampanga');

Crate table city

CREATE TABLE IF NOT EXISTS `city` (
  `city_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `state_id` bigint(20) NOT NULL,
  `country_id` int(11) NOT NULL,
  `city_name` varchar(255) NOT NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `city` (`city_id`, `state_id`, `country_id`, `city_name`) VALUES
(1, 1, 98, 'Olongapo City'),
(2, 1, 98, 'Iba'),
(3, 2, 98, 'Angeles City'),
(4, 2, 98, 'San Fernando');

//index.php
<?php
	include("functions.php");		
	$db = new PHP_fun();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Ajax, Php class list box </title>
<script language="javascript"  type="text/javascript" src="validation.js"></script>
<script language="javascript" type="text/javascript">
	function getCities(id)
	{
		var obj = document.form1;
		if (id != "")
		{
			url = "getCities.php?stateid="+id;
			http.open("GET", url, true);
			http.onreadystatechange = getCitiesResponse; 
			http.send(null);
		}
	}
	
	function getCitiesResponse()
	{
		//alert(http.readyState);
		var obj = document.form1;
		if (http.readyState == 4)
		{
			var result = trimString(http.responseText);
			if (result != '' && result != 'undefined')
			{
				clearBox(obj.city);
				obj.city.options[0] = new Option("-City-", "");
				var result_line_arr = result.split("###");
				for (i=0;i<result_line_arr.length;i++)
				{
					var result_arr = result_line_arr[i].split(":");
					var code = result_arr[0];
					var name = result_arr[1];
					obj.city.options[i+1] = new Option(name, code);
				}
			}		
		}
	}
</script>
</head>
<body>
<table width="60%" border="0" cellspacing="0" cellpadding="5">
<form action="" method="post" name="form1">
  <tr>
      <td align="right" class="verdana11">State :</td>
      <td align="left" class="verdana11">
      	<select name="state" id="state" onchange="javascript: getCities(this.value);">
        	<option value="">-State-</option>
            <?php
				$sql = "select * from state";
				$rs = $db->select_row($sql);
				for($i=0;$i<count($rs);$i++)
				{ ?>
					<option value="<?=$rs[$i]['state_id']?>"><?=$rs[$i]['state_name']?></option>
				<?php }
            ?>
        </select>     
	</td>
  </tr>
    <tr>
      <td align="right" class="verdana11">City : </td>
      <td align="left" class="verdana11">
		  <select name="city" id="city" style="width:150px;">
				<option value="">-City-</option>
		  </select>      
	  </td>
    </tr>
</form>
</table>
</body>
</html>
//funtion.php
<?php
	class PHP_fun 
	{
		function getConfig()
		{
			$this->DB_SERVER = 'localhost'; 
			$this->DB_USER = 'root'; 
			$this->DB_PASS = ''; 
			$this->DB_NAME = 'test'; 
		
		}
		function __construct()
		{
			$this->getConfig();
			$Conn = mysql_connect($this->DB_SERVER, $this->DB_USER, $this->DB_PASS);
			if (!$Conn)
				die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn));
			$DB_select = mysql_select_db($this->DB_NAME, $Conn);
			if (!$DB_select)
				die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn));
		}

		function select_row($sql)
		{
			if ($sql!="")
			{
				$result = mysql_query($sql) or die("Error: ".mysql_errno().":- ".mysql_error());
				if ($result)
				{
					while($row = mysql_fetch_array($result))
						$data[] = $row;
				}
				return $data;
			}
		}
	}
?>	
//getCities.php
<?php
	include("functions.php");		
	$db = new PHP_fun();
	$str = "";
	$stateid = trim($_REQUEST['stateid']);
	if ($stateid != "")
	{
		$sql = sprintf("SELECT city_id, city_name FROM city WHERE state_id = '%d' ", $stateid);
		$rs = $db->select_row($sql);
		if (count($rs) > 0)
		{
			for($i=0;$i<count($rs);$i++)
			{
				$str .=  $rs[$i]['city_id'].":".$rs[$i]['city_name']."###";
			}
			echo $str = substr($str,0,-3);
		}
	}
?>
//validation.js
// ajax oject 
		function getHTTPObject() 
		{ 
			var xmlhttp; 
			/*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/  
			if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
			{ 
				try { 
					xmlhttp = new XMLHttpRequest(); 
				} 
				catch (e) { 
					xmlhttp = false; 
				} 
			} 
			return xmlhttp;
		}
		var http = getHTTPObject(); // We create the HTTP Object 
		
		function clearBox(ObjselBox)	
		{
			for(i=ObjselBox.length-1; i>=0; i--)
			{
				deleteOption(ObjselBox, i);
			}
		}
		
		function deleteOption(theSel, theIndex)
		{	
			var selLength = theSel.length;
			if(selLength > 0)
			{
				theSel.options[theIndex] = null;
			}
		}
		
		// end ajas object
		
		
		function trimString(str)
		{
			return str.replace(/^\s+|\s+$/g, '');
		}

Related Post