Tuesday 13 November 2012

country state city ajax dropdown

PHP MySQL country state city ajax drop down with database.

When you are creating triple or more than 2 dependent dropdown then you might need to take care of parents and child dropdowns. Means if you make changes to parent then your child nodes should get affected too.

Here in this country state city dropdown as you change country then it is required to change states. and when states get changed required to change cities too.

Below code works well in all modern browsers like Chrome, mozilla, IE9/8/7 and works well so copy and enjoy it

Database design/structure for country, state and city tables

CREATE TABLE IF NOT EXISTS `country` (
  `Country_Id` varchar(3) NOT NULL,
  `name` varchar(60) NOT NULL,
  `continent_code` varchar(30) NOT NULL,
  `tel_code` varchar(5) NOT NULL,
  PRIMARY KEY (`Country_Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

`continent_code` and `tel_code` is not necessary yet you can avoid that fields.

CREATE TABLE IF NOT EXISTS `state` (
  `state_id` varchar(6) NOT NULL,
  `country_id` varchar(3) NOT NULL,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`state_id`),
  KEY `Country_Id` (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `city` (
  `city_id` varchar(10) NOT NULL,
  `state_id` varchar(6) NOT NULL,
  `city_name` varchar(50) NOT NULL,
  PRIMARY KEY (`city_id`),
  KEY `state_id` (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- foreign key constrains for table state and city (If you dont know simply avoid this)

ALTER TABLE `city`
  ADD CONSTRAINT `city_ibfk_1` FOREIGN KEY (`state_id`) REFERENCES `state` (`state_id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `state`
  ADD CONSTRAINT `state_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`Country_Id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- End of database structure.

Javascript Code

<script>
var xmlhttp;
function ajaxFunction(url,myReadyStateFunc)
{
   if (window.XMLHttpRequest)
   {
      // For IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
   }
   else
   {
      // For IE5, IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange= myReadyStateFunc;        // myReadyStateFunc = function
   xmlhttp.open("GET",url,true);
   xmlhttp.send();
}

function getState(x)
{
    // in second argument of ajaxFunction we are passing whole function (onreadystatechange function).
    // Goto getState.php code
    ajaxFunction("getState.php?cid="+x, function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
var s = xmlhttp.responseText;    //   s = "1,2,3,|state1,state2,state3,"
s=s.split("|");                              //   s = ["1,2,3,", "state1,state2,state3,"]
sid = s[0].split(",");                    //  sid = [1,2,3,]
sval = s[1].split(",");                   //  sval = [state1, state2, state3,]
st = document.getElementById('state')
st.length=0
for(i=0;i<sid.length-1;i++)
{
st[i] = new Option(sval[i],sid[i])
}
getCity(-1) // emptying the city.
        }
    });
}
function getCity(x)
{
    // in second argument of ajaxFunction we are passing whole function.
   // Goto getCity.php code
   ajaxFunction("getCity.php?sid="+x, function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
var c = xmlhttp.responseText;
c=c.split("|");
cid = c[0].split(",");
cval = c[1].split(",");
ct = document.getElementById('city')
ct.length=0
for(i=0;i<cid.length-1;i++)
{
ct[i] = new Option(cval[i],cid[i])
}
        }
    });
}
</script>
<style>
select{width:270px;size:10}
</style>

HTML Code

<table>
<tr>
<td>Country </td>
<td>:&nbsp;<select name="country" id="country" onchange="getState(this.value)">
<option value="-1">Select Country</option>
<?php
$cntry = mysql_query("SELECT `Country_Id`, `name` FROM country ORDER BY `name` ASC");
while($row = mysql_fetch_assoc($cntry))
{
echo '<option value="'.$row['Country_Id'].'">'.$row['name'].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>State </td>
<td>:&nbsp;<select name="state" id="state" onchange="getCity(this.value)">
<option value="-1">Select State</option>
</select>
</td>
</tr>
<tr>
<td>City </td>
<td>:&nbsp;<select name="city" id="city" >
<option value="-1">Select City</option>            
</select>
</td>
</tr>
</table>

PHP Code for getState.php

$link = mysql_connect("localhost","root","");
$dbSelected = mysql_select_db('pra_countrystate');
$id="-1,";
$sname="Select State,";
$cid = $_GET['cid'];
if($cid=="-1")
{
$response = $id."|".$sname;
echo $response;
}
else
{
$result = mysql_query("SELECT `state_id`, `name` FROM `state` WHERE `country_id` = ".$cid." ORDER BY `name` ASC");
while($row = mysql_fetch_assoc($result))
{
$id .=$row['state_id'].","; 
$sname .=$row['name'].","; 
}
$response = $id."|".$sname;
echo $response;
}
?>

PHP Code for getCity.php

<?php
$link = mysql_connect("localhost","root","");
$dbSelected = mysql_select_db('pra_countrystate');
$id="-1,";
$cname="Select City,";
$sid = $_GET['sid'];
if($sid=="-1")
{
$response = $id."|".$cname;
echo $response;
}
else
{
$result = mysql_query("SELECT `city_id`, `city_name` FROM `city` WHERE `state_id` = ".$sid." ORDER BY `city_name` ASC");

while($row = mysql_fetch_assoc($result))
{
$id .=$row['city_id'].",";
$cname .=$row['city_name'].",";
}
$response = $id."|".$cname;
echo $response;
}
?>

Sunday 4 November 2012

ajax calling multiple function with same xmlhttprequest object

If you are not familiar to ajax then check out ajax introduction click here 

As explained in previous post we need to create XMLHttpRequest object for sending request.

If you have morethan one AJAX call on one page then you should reuse them. You should create one standard ajax XMLHttpRequest object and that should be called times.

And don't worry if you use morethan one XHR (XMLHttpRequest) object on same page. It won't create any problem. But better coding practice it is suggested to reduce code.

<script>
var xmlhttp;
function ajaxFunction(url,myReadyStateFunc)
{
   if (window.XMLHttpRequest)
   {
      // For IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
   }
   else
   {
      // For IE5, IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange= myReadyStateFunc;
   xmlhttp.open("GET",url,true);
   xmlhttp.send();
}

function myFunction()
{
    ajaxFunction("ajaxTest.txt",function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    });
}
function myFunction1()
{
   ajaxFunction("ajaxTest.txt",function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
            document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;
        }
    });
}
</script>

<body>
<div id="myDiv"><h2>Default Text Click Button to change Text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button> 

<div id="myDiv1"><h2>Default text Click Button to change Text</h2></div>
<button type="button" onclick="myFunction1()">Change Content</button>
</body>

Here myFunction() and myFunction1() are two different functions.
While ajaxFunction()is ajax function which is creating request and response.

First we are calling myFunction() function in which we are calling ajaxFunction() with two arguments - url for server communication and in second argument we are passing whole onreadystatechange() function, means on response what we are gonna do.

both function having onreadystatechange function which are to update myDiv and myDiv1. myDiv and myDiv1 are id of div. which will be replaced by respective AJAX call response.

AJAX introduction and learning


What is AJAX

AJAX stands for Asynchronous JavaScript and XML.
AJAX is used to exchange data with server, and updating just part of webpage rather than updating whole page.

How ajax works
XMLHttpRequest object
Sending request to server
Receiving server response
onreadystatechange function
AJAX expamples - Call multiple functions with same XMLHttpRequest object.

How AJAX Works

  • Creating XMLHttpRequest object (creating object)
  • With that object send HttpRequest (sending request)
  • Server will process HttpRequest
  • Server creates response and send data back to browser.
  • Browser process returned data using javascript (receiving resutl)
  • Browser updates part of page.(displaying result)

AJAX - Creating an XMLHttpRequest Object

XMLHttpRequest object is used to exchange data with server and receiving response with help of that part of page can be updated.

All modern browser now a days supports the XMLHttpRequest object except some browsers like IE5 and IE6. IE5 and IE6 uses ActiveXObject.

All modern browsers like IE7+, Firefox, Chrome, Safari and Opera supports XMLHttpRequest object

Syntax
variable=new XMLHttpRequest();   
variable=new ActiveXObject("Microsoft.XMLHTTP");   // for older browsers (IE5 & IE6)
 Example
var xmlhttp;
if (window.XMLHttpRequest)
{
        // For IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
}
else
{
       // For IE5 & IE6
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

Sending Request to Server

To send request to server we use open() and send() methods

Syntax
xmlhttp.open(methodurlasync);
xmlhttp.send();
Method Description
open(method,url,async) It specifies type of request, url for communication and asynchronous true of false.
method : specifies request type GET or POST
url : File location/ communicating file on server
async : true - asynchronous and false - synchronous
send(string) sending request to the server.
string : It is used when the request method is POST

GET Request : 
GET simpler and faster than post. All the data which are to be sent, are appended to the url. no need to send any string with send method. It is mainly used in searching and updating small insecure data.
xmlhttp.open("GET","page.php?a=" +valueA+"&b="+valueB ,true);
xmlhttp.send();
POST Request
POST method is more secure and can send very large amount of data without displaying it in url.
To send Form data with POST we need to provide HTTP header with setRequestHeader(). and specify data into send which you want to send.
xmlhttp.open("POST","page.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("a="+valueA+"&b="+valueB); // valueA and valueB are javascript variables
Method Description
setRequestHeader(header,value) setting up request header.
header : specifies header name/type
value : specifies header value.
async - true or false
true : specifies that ajax runs asynchronously. And you must specify the onreadystatechange().
false : specifies that ajax runs synchronously. Javascript will not run until it receives the response from the server. If server is busy/slow it will hang up until response received.
 If you are using false then don't use onreadystatechange() function.

example for "true" (asynchronous)
xmlhttp.onreadystatechange=function()
{
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      }
}
xmlhttp.open("GET","page.php",true);
xmlhttp.send();
 if you use "false" instead "true" then just simply receive response after send();


example for "false" (synchronous)
xmlhttp.open("GET","page.php",true);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;


Receiving Server Response

To receive response from server use responseText or responseXML property of XMLHttpReqest object.

responseText : get the response data as a string.
responseXML: get the response data as XML data.

onreadystatecnange event

When a request to a server is sent, we may want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:

Method Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds status of the XMLHttpRequest. values are from 0 to 4:
0: request not initialized.
1: server connection established.
2: request received.
3: processing request.
4: request finished and response is ready.
status 200: "OK"
404: Page not found

examples
xmlhttp.onreadystatechange=function()
{
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      }
}

Check out Examples


how to install pear on wamp server

Let's have look at how to install go-pear in wamp server

First download go-phear : download PEAR or save file as .phar from http://pear.php.net/go-pear

Save above file where your php.exe is located means your php executable directory.

Now open cmd as administrator - right click on cmd and click on run as administrator. And run following command.
Move to your php executable directory and type :

C:\wamp\bin\php\php5.3.0>php -d phar.require_hash=0 PEAR/go-pear.phar(drive may change as per your installed drive)

Reply to “Are you installing a system-wide PEAR or a local copy?” with “local” or "system". When prompted, set each directory to the following scheme (note: the php version may differ):

Below is a suggested file layout for your new PEAR installation. To change individual locations, type the number in front of the directory. Type 'all' to change all of them or simply press Enter to accept these locations.

1. Installation base ($prefix): C:\wamp\bin\php\php5.3.0
2. Temporary directory for processing: C:\wamp\bin\php\php5.3.0\tmp
3. Temporary directory for downloads: C:\wamp\bin\php\php5.3.0\tmp
4. Binaries directory: C:\wamp\bin\php\php5.3.0
5. PHP code directory ($php_dir): C:\wamp\bin\php\php5.3.0\pear
6. Documentation directory: C:\wamp\bin\php\php5.3.0\pear\docs
7. Data directory: C:\wamp\bin\php\php5.3.0\pear\data
8. User-modifiable configuration files directory: C:\wamp\bin\php\php5.3.0\pear\cfg
9. Public Web Files directory: C:\wamp\www
10. Tests directory: C:\wamp\bin\php\php5.3.0\pear\tests
11. Name of configuration file: C:\wamp\bin\php\php5.3.0\pear.ini
12. Path to CLI php.exe: C:\wamp\bin\php\php5.3.0\.

1-12, 'all' or Enter to continue:

And your installation will begin.

At the end it will generate a .reg file, on which you have to double click to enter this information into registry.

Install again using C:\wamp\bin\php\php5.3.0>php go-pear.phar which will remove if any error were generated.

Still You are not done: (your version and directory may differ)
  • open your php.ini file which is located in  C:\wamp\bin\php\php5.3.0\

    • find "Paths and Directories"
      Add - include_path = ".;C:\wamp\bin\php\php5.3.8\pear"

  • Now open php.ini file from your apache directory  C:\wamp\bin\apache\apache2.2.11\bin\php.ini

    • find "Paths and Directories"
      Add - include_path = ".;C:\wamp\bin\php\php5.3.8\pear"
Restart your apache server

Change the Windows PATH environment variable to include c:\wamp\bin\php\php5.3.0 (in Windows Vista: Start->Control Panel->System and Maintenance->System->Advanced System Settings->Environment Variable. Edit the PATH system variable and add c:\wamp\bin\php\php5.3.0). 

Now start a Windows command prompt and type pear. It will list all the pear commands. pear list will list all PEAR packages current installed. Use pear install -o <package> to install a package ( -o will install required dependencies).


You may need to add the following environment variables to the environment.

(create .htaccess file and put following code into .htaccess file and save .htaccess file into your PEAR directory)

php_value include_path “ C:\wamp\bin\php\php5.3.0\PEAR”
php_value error_reporting 0 

PHP_PEAR_BIN_DIR=C:\wamp\bin\php\php5.3.0
PHP_PEAR_DATA_DIR=C:\wamp\bin\php\php5.3.0\PEAR\data
PHP_PEAR_DOC_DIR=C:\wamp\bin\php\php5.3.0\PEAR\docs
PHP_PEAR_INSTALL_DIR=C:\wamp\bin\php\php5.3.0\pear
PHP_PEAR_PHP_BIN=C:\wamp\bin\php\php5.3.0\php.exe
PHP_PEAR_SYSCONF_DIR=C:\wamp\bin\php\php5.3.0
PHP_PEAR_TEST_DIR=C:\wamp\bin\php\php5.3.0\PEAR\tests

And you can install PEAR front end too. for viewing on wamp server

c:\wamp\bin\php\php5.3.0>pear install PEAR_Frontend_Web


During installation if you find and DEPRECATED message then just ignore them as they are not ERROR.

After a package is installed, the documentation for the package will be in a newly created folder under C:\wamp\bin\php\php5.3.0\PEAR\docs\.
The C:\wamp\bin\php\php5.3.0\PEAR\test\ folder typically contains a sample test php script, to test the package.
Some packages are in beta. To install them you first need to set the preferred release to beta: pear config-set preferred_state beta. Then after installing the beta package do pear config-set preferred_state stable.

PEAR_Frontend_Web package, which was in Beta when this was written, is a web-based front-end alternative to the command line PEAR package manager. To install it open a Windows command prompt and do:
c:\wamp\bin\php\php5.3.0>pear install PEAR_Frontend_Web