Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

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(method, url, async);
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


Saturday, 18 August 2012

php list all directories and its files and subdirectory

Often you may need to list all the directories and subdirectory/files in tree structure in your side panel as the content or examples. This kind of things are mainly required in Educational or Learning blogs.

By looking those required here I have created one side panel which will help you to create yours one and also i have given full code explanation for creating / listing all the directories and its files. See code and its output as listed  below.

It it also very helpful to display all the image files of some directory without typing code for all Images. If you use following code then you can simply place the images in to your folder and you have done. Means all the image files will be loaded itself with php code. 

It will give you freedom to change your files/images at anytime without worrying about linking it to pages.



FILE NAME : index.php

<html>
<head>
           <title>Untitled Document</title>
           <link href="styles.css" rel="stylesheet" />

            <script type="text/javascript">
                        /* To show code into iframe set source of that file in iframe*/
                        function loadContent(x)
                        {
                                    document.getElementById('frmContent').src = x;
                         }
            </script>
</head>

<body>
<div id="body">
    <div id="header">
        <h1>Mukund </h1>
        <hr style="border:#A63600 3px solid"/>
    </div>

    <div id="container">
      <div id="sidebarLeft">
        <ul>
<?php
// set handle for directory resource
// '../' replace it with your desire directory.
        if ($handle = opendir('../')) {
// black list files which you dont wanna include. 
// you can add more files in following manner.
            $blacklist = array('.', '..', 'youDirectory');
        
          while (false !== ($file = readdir($handle)))
         {
                if (!in_array($file, $blacklist)) {
                    echo '<li>'.$file.'</li>';

                    // Set Directory path with latest directory here i have given path from root directory
                  $directory = "../".$file."/";

    // list each file of Directory - $file
    echo '<ul>';
         // for HTML files
$htmlFiles = glob($directory . "*.html" );
foreach($htmlFiles as $htmlFile)
{
echo '<li>
                                  <a href="#" onclick="loadContent(\''.$htmlFile.'\')">'.basename($htmlFile).'</a>
                                 </li>';
}

// Simillarly For PHP Files
$phpFiles = glob($directory . "*.php" );
foreach($phpFiles as $phpFile)
{
echo '<li>
                                  <a href="#" onclick="loadContent(\''.$phpFile.'\')">'.basename($phpFile).'</a>
                                 </li>';
}
           echo '</ul>';
/ / End of file listing.
             }
           }
          // close the directory handle.
            closedir($handle);
       }
       ?>
        </ul>           
    </div>
    <div id="content">
        <p>Hi, Click on respective pages to view content of it.</p>
        <iframe src="" id="frmContent"></iframe>
    </div>
    </div>
</div>
</body>
</html>


STYLESHEET : styles.css

body{
width:994px;
margin:0 auto;
font-family:Verdana, Geneva, sans-serif;
font-size:14px;
}
#body{
background:#DAEBFC;
}
#header{
padding:15px;
height:60px
}
#container{
padding:15px;
overflow:auto
}
#sidebarLeft{
float:left;
width:160px;
border:1px solid #CCC;
padding:5px;
font-size:12px
}
#sidebarLeft ul{
padding:0;
margin:0
}
#sidebarLeft ul li{
padding:5px;
list-style:none;
font-weight:bold;
font-size:16px
}
#sidebarLeft ul ul{
margin-left:15px
}
#sidebarLeft ul ul li{
font-weight:normal;
font-size:12px;
padding:2px
}
#content{
float:left;
padding:0 0 15px 15px;
width:775px
}
#content iframe{
width:770px;
height:720px;
margin:o auto;
overflow:scroll;
border:1px solid #ccc
}


Out put in IE9



Explanation of Code

Functions: 
opendir(): The opendir() function opens a directory handle to be used by the closedir(),    readdir(), and rewinddir() functions.This function returns a directory stream on success and FALSE and an error on failure. You can hide the error output by adding an '@' in front of the function name. 
readdir(): The readdir() function returns an entry from a directory handle opened by opendir().
This function returns a filename on success and FALSE on failure. The entries are returned in the order in which they are stored by the filesystem.
glob(): The glob() function returns an array of filenames or directories matching a specified pattern.This function returns an array of files/directories, or FALSE on failure.
Code Explanation

In above PHP code First you are creating a handle for your directory which is given as directory('../'). For current directory replace '../' to './'. Now create blacklist array which you don't want to display.

While loop will executed for times until it will false the readdir handle. In While loop return value of readdir() is checked. Here we are checking return value is identical and of same type too. If any directory entry whose name evaluates to FALSE will stop the loop.

Next, If loop will check for blacklist files directory if any files/directory that falls into blacklist it will be skipped. in_array($file, $blacklist) function is used to check that $file is in the $blacklist array or not.

Now, simply use the glob function to list all the matching files. glob($directory.'*.jpg') which will list all the files whose extension is .jpg. In above example I have used listed .php and .html files. For your specific files you can replace extension as per your requirement.

Last close the handle and terminate the code.

Thursday, 8 March 2012

HTTP FORM POST in PHP using AJAX


This example demonstrates HTTP FORM POST complete HTML form to the server and displaying the response using AJAX.

HTML Page
<html>
<head>
<title>PHP using AJAX</title>
<script type="text/javascript">
 
var time_variable;
 
function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
 
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
 
function ajaxFunction() {
  var getdate = new Date();  //Used to prevent caching during ajax call
  if(xmlhttp) {
   var txtname = document.getElementById("txtname");
    xmlhttp.open("POST","testing.php",true); //calling testing.php using POST method
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("txtname=" + txtname.value); //Posting txtname to PHP File
  }
}
 
function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}
</script>
<body>
<form name="myForm">
<table>
 <tr>
  <td>Enter Name</td>
  <td><input type="text" name="txtname" id="txtname" /></td>
 </tr>
 <tr>
  <td colspan="2"><input type="button" value="Submit" onclick="ajaxFunction();" /></td>
 </tr>
</table>
<div id="message" name="message"></div>
</form>
</body>
</head>
</html>
PHP Code

< ?
 
$a = $_POST['txtname'];
 
echo "Good Morning".$a;
 
 
?>




Explanation for the AJAX Code

Here i have declared 3 JavaScript function:

getXMLObject() – Responsible for creating the AJAX Object depending on the browser

ajaxFunction() – Responsible for calling PHP page through AJAX call
handleServerResponse() – Responsible for displaying the data retrieved from the server

How the AJAX Code Works:
  • When the page loads i am creating an AJAX Object by calling the getXMLObject() function and returning the object created in the xmlhttp variable
  • When the user clicks on the input Button, ajaxFunction() gets called which checks for whether the Ajax Object is created or not and depending on that calls the remote script. Here a function handler handleServerResponse is also defined for retrieving the value from the server
  • When the readystate of the AJAX call reaches 4 and the http status is 200 we pass the data fetched from the server to the textbox

Explanation for the PHP Code

  • I am calling $_POST for fetching the post content send through Ajax Call
  • Finally i am calling echo to send the response back to the calling page