Sunday, September 11, 2011


AJAX DEPENDENT DROP DOWN

To know the basics of Ajax refer http://w3schools.com/ajax/default.asp

Say your pull down menu Caste is dependent with the pull down menu Religion as given below
<select name="religion" id="religion" onchange="showCaste(this.value)">
           // Your options here
</select>

<select name="caste" id="caste">
           // Your options here
</select>

In the religion pull down menu we add a property onchange. That is when we select a particular religion the function showCaste will be called. this.value is the value of the selected religion.
The below javascript code should be included in the head section of the page.

// JavaScript Document
<script  type="text/javascript">
function showCaste(religion_id)
{             
                                var xmlhttp;
                                if (window.XMLHttpRequest)
                                  xmlhttp=new XMLHttpRequest();
                                else if (window.ActiveXObject)
                                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                                else
                                  alert("Your browser does not support XMLHTTP!");
                                xmlhttp.onreadystatechange=function()
                                {
                                                if(xmlhttp.readyState==4)
                                                {
                                                                var ss=document.getElementById('caste');                 
                                                                ss.innerHTML= xmlhttp.responseText;                                        
                                                }
                                }
                               xmlhttp.open("GET","showCaste.php?religion="+religion_id+"&token="+Math.random()*5,true);
                              xmlhttp.send(null);
}
</script>


The above code calls the showCaste.php page where we have written the code to populate the caste pulldown.

//showCaste.php
<?php
//steps to initiate connection to the database
$religion=$_GET['religion'];
$result = mysql_query("SELECT * FROM caste WHERE religion_id='".$religion."'");
while($row = mysql_fetch_array($result))
{
                $pullDown.="<option value=".$row['id'].">".$row['display']."</option>";
}
echo $pullDown;
?>

No comments:

Post a Comment