SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Addict
    Join Date
    Nov 2002
    Location
    Maryland
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:
    Code HTML4Strict:
    <!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>

  2. #2
    SitePoint Zealot shoorace's Avatar
    Join Date
    Jun 2005
    Location
    Florida
    Posts
    142
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    Code SQL:
    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:
    PHP Code:
    <?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 .= '<option value="'.$rowSchool['Id'].'">'.$rowSchool['Name'].'</option>';
            }
            echo 
    $strOptions;
            exit;
        }
    ?>
    ajaxform.php:
    Code HTML4Strict:
    <!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">
    // 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);
    }
    </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" id="listSchools" onchange="populate();">
    <?php
    	$rsSchool = mysql_query("SELECT * FROM tbl_schools", $link);
    	while($rowSchool = mysql_fetch_assoc($rsSchool)){
    		echo '<option value="'.$rowSchool['Id'].'">'.$rowSchool['Name'].'</option>';
    	}
    ?>
    </select>
    </p>
    <p>
    Add new school:<br />
    <input type="text" name="school_name" size="30" /><br />
    <input type="button" name="submit" value="submit" onclick="xmlHandlerPost('listSchools',this.form.school_name.value)" />
    </p>
    </form>
    </body>
    </html>

  3. #3
    SitePoint Addict
    Join Date
    Nov 2002
    Location
    Maryland
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The code worked shoorace! Thanks so much!

  4. #4
    SitePoint Addict
    Join Date
    Nov 2002
    Location
    Maryland
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:
    Code HTML4Strict:
    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?

  5. #5
    SitePoint Addict
    Join Date
    Nov 2002
    Location
    Maryland
    Posts
    307
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Any ideas?

  6. #6
    SitePoint Member
    Join Date
    Mar 2007
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    this code is not working in Internet explorer can anyone tell what needs to be changed to make it work in IE

  7. #7
    SitePoint Addict eanimator's Avatar
    Join Date
    Sep 2005
    Posts
    396
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <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:
    PHP Code:
    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;        
        }



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •