Using AJAX to Populate Dropdown menu

Hello,
Can anyone provide a link for a tutorial to do the following php task:

I want to allow users to update a school dropdown menu without the page refreshing. The schools would be added to MySql and then retrieved using PHP and AJAX to populate the menu.

Thanks for any help.

Here is what the HTML would look like:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function populate()
{
if (document.form1.select.value != "")
{
document.form1.textfield.value = document.form1.select.value;
}
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
<p>
//****** This needs to be populated dynamically using php ajax from MySQL. ****///
<select name="select" onchange="populate();">
<option value="1">School 1</option>
<option value="2">School 2</option>
<option value="3">School 3</option>
<option value="4">School 4</option>
</select>
</p>
<p>
Add new school:<br />
<input type="text" name="school_name" size="30" /><br />
<input type="button" name="submit" value="submit" />
</p>
</form>
</body>
</html>

Try this:

create database if not exists `school`;

USE `school`;

CREATE TABLE `tbl_schools` (
  `Id` int(11) unsigned NOT NULL auto_increment,
  `Name` varchar(50) NOT NULL,
  PRIMARY KEY  (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=11;

insert  into `tbl_schools`(`Id`,`Name`) values (1,'School 1'),(2,'School 2'),(3,'School 3'),(4,'School 4');

ajaxform.php:


&lt;?php
	$link = mysql_connect("localhost","root","");
	$db = mysql_select_db("school",$link);
	
	if(isset($_POST['mode'])){
		//print_r($_POST);
		mysql_query("INSERT INTO tbl_schools (Name) VALUES ('".$_POST['data']."')", $link);
		
		$rsSchool = mysql_query("SELECT * FROM tbl_schools", $link);
		$strOptions = '';
		while($rowSchool = mysql_fetch_assoc($rsSchool)){
			$strOptions .= '&lt;option value="'.$rowSchool['Id'].'"&gt;'.$rowSchool['Name'].'&lt;/option&gt;';
		}
		echo $strOptions;
		exit;
	}
?&gt;

ajaxform.php:


&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
&lt;title&gt;Untitled Document&lt;/title&gt;
&lt;script type="text/javascript" language="javascript"&gt;
// JavaScript Document
function getHTTPObject(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}
var http = getHTTPObject(); // We create the HTTP Object

function xmlHandlerPost(outputData, inputData) { 
	if(inputData=="")
		return false;
		
	var vars = "mode=add&data=" + inputData;
	var url = "ajaxform.php";
	
	http.open("POST", url , true);
	http.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 
  http.onreadystatechange = function() {  
  
		if (http.readyState == 4) {     
			results = http.responseText 
			//alert(results);
			document.getElementById(outputData).innerHTML = results;
		};
  }    
  http.send(vars);
}
&lt;/script&gt;
&lt;/head&gt;
 
&lt;body&gt;
&lt;form id="form1" name="form1" method="post" action=""&gt;
&lt;p&gt;
//****** This needs to be populated dynamically using php ajax from MySQL. ****///
&lt;select name="select" id="listSchools" onchange="populate();"&gt;
&lt;?php
	$rsSchool = mysql_query("SELECT * FROM tbl_schools", $link);
	while($rowSchool = mysql_fetch_assoc($rsSchool)){
		echo '&lt;option value="'.$rowSchool['Id'].'"&gt;'.$rowSchool['Name'].'&lt;/option&gt;';
	}
?&gt;
&lt;/select&gt;
&lt;/p&gt;
&lt;p&gt;
Add new school:&lt;br /&gt;
&lt;input type="text" name="school_name" size="30" /&gt;&lt;br /&gt;
&lt;input type="button" name="submit" value="submit" onclick="xmlHandlerPost('listSchools',this.form.school_name.value)" /&gt;
&lt;/p&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

The code worked shoorace! Thanks so much!

This code works great, but does anyone know of a way to populate the dropdown menu from a popup window? What would happen then the following HTML code would be in a popup:


Add new school:<br />
<input type="text" name="school_name" size="30" /><br />
<input type="button" name="submit" value="submit" />
</p>

Then when a user submits a new school in the popup window the parent window dropdown menu would automatically update without refreshing.

Is this possible?

Any ideas?

this code is not working in Internet explorer can anyone tell what needs to be changed to make it work in IE


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

function createRequestObject() {
	var xmlhttp;
	try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }
  catch(e) {
    try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
    catch(f) { xmlhttp=null; }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
  	xmlhttp=new XMLHttpRequest();
  }
	return  xmlhttp;
}

function doRequest(url,method,data,_handler){
	http=createRequestObject()

	if (http==null)
		alert ("Browser does not support HTTP Request.");
		
	http.open(method,  url);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	http.onreadystatechange = _handler;
	if(method == "POST"){
		if(data == null){
			alert("No data provided to post");
		}else{
			http.send(data);
		}
	}else{
		http.send(null);	
	}
}
</script>

Include the above script and use “doRequest” function.

Example:


var post_data = "field1=1&field2=2";

doRequest("populateCombo.php","POST",post_data,'my_handler');

functon my_handler(){
      if((http.readyState == 4)&&(http.status == 200)){
		var response = http.responseText;		
	}
}