Category: Uncategorized


Blog Moved

I have moved this blog from here to CodePilgrim. I have copied some of the posts also over there. Please follow me there.

Here we are going to see basic AJAX script in play. Here I’m writing a script which populates a drop down box with states according to the countries selected in another drop down. So let’s see how it is done.

Given below are the drop downs in play (Note: I’ve only used a few data)

Country: <select name="country" onchange="return onchangeajax(this.value);" >
 <option value=""   selected="selected" >Select</option>
 <option value="USA"  >USA</option>
 <option value="India"  >India</option>
 <option value="UK"  >UK</option>
 </select><br />
 State: <div id="statediv"><input type="text" name="state" /></div>
 <input type="submit" name="signupsubmit" value = "Sign Up" />

Now as we see we have written a JavaScript function call on changing the items in drop down. Given below is the Ajax code to be embedded in the page.

function onchangeajax(pid)
 {
 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }

 var url="changestate.php"
 url=url+"?pid="+pid
 url=url+"&sid="+Math.random()
 document.getElementById("statediv").innerHTML='Please wait..<img border="0" src="images/ajax-loader.gif">'
 if(xmlHttp.onreadystatechange=stateChanged)
 {
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 return true;
 }
 else
 {
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 return false;
 }
 }

 function stateChanged()
 {
 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("statediv").innerHTML=xmlHttp.responseText
 return true;
 }
 }

 function GetXmlHttpObject()
 {
 var objXMLHttp=null
 if (window.XMLHttpRequest)
 {
 objXMLHttp=new XMLHttpRequest()
 }
 else if (window.ActiveXObject)
 {
 objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
 }
 return objXMLHttp;
 }
</script>

Now we see that in the Ajax script it is calling another file ‘changestate.php’. This is the file which has the code that should populated in the ‘statediv’

<?php
 $val=$_REQUEST['pid'];
 if($val == 'USA')
 {
?>
<select name="state">
 <option value="">--Select--</option>
 <option value="Alabama">Alabama</option>
 <option value="Alaska">Alaska</option>
</select>
<?php
 }
 else if($val == 'India')
 {
?>
<select name="state">
 <option value="">--Select--</option>
 <option value="Karnataka">Karnataka</option>
 <option value="Kerala">Kerala</option>
</select>
<?php
 }
 else
 {
?>
<input type="text" name="state" />
<?php
 }
?>

[/sourcecode]