www.webdeveloper.com
Results 1 to 2 of 2

Thread: PHP/Javascript/Jquery -Selecting a dropdown item should dynamically display another

  1. #1
    Join Date
    Jul 2010
    Posts
    4

    PHP/Javascript/Jquery -Selecting a dropdown item should dynamically display another

    Any idea on how to get this done...
    I have two text fields one is TECH field and another is JOB NUMBER... If I type a number in the tech field and If I select a number from the autopopulated/autosuggested list of tech number(which is queried from the database) it should display a dropdown list of JOBNUMBERS associated to that particular TECH number..... ( The TECH is not a Primary key in database)

    This is the code that I have to fetch the and the tech number will be the autosuggest field for which I have used JQUERY.....


    <script type="text/javascript" src="jquery-1.2.1.pack.js"></script>
    <script type="text/javascript">
    function suggest(inputString){
    if(inputString.length == 0) {
    $('#suggestions').fadeOut();
    } else {
    $('#tech').addClass('load');
    $.post("rpc.php", {queryString: ""+inputString+""}, function(data){
    if(data.length >0) {
    $('#suggestions').fadeIn();
    $('#suggestionsList').html(data);
    $('#tech').removeClass('load');
    }
    });
    }
    }

    function fill(thisValue) {
    $('#tech').val(thisValue);
    //$('#suggestions').hide();
    setTimeout("$('#suggestions').fadeOut();");
    }

    </script>

    <style>
    ........
    ........
    </style>
    </head>

    <body>

    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">

    <table width="300" height="100" border="0" cellpadding="0" cellspacing="0">
    <tr>
    <td>
    <div id="suggest" align="left">Tech ID:
    <input type="text" size="4" name="tech" id="tech" value="" maxlength="4" onkeyup="suggest(this.value)" onblur="fill()" onchange="jobDropDown(this)" class="" />
    <div class="suggestionsBox" id="suggestions" style="display: none;">
    <img src="arrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
    <div class="suggestionList" id="suggestionsList"> </div>
    </div>
    </div></td>
    <td>Job Number: <input type="text" name="Job" id="Job" maxlength="6" value=""/></td>
    <td><input type="submit" name="search" id="search" value="Search"/></td>
    </tr>
    </table>
    </form>
    </body>
    </html>


    The database connection code : ( The TECH is not a Primary key in database and a single tech can have multiple jobs )

    <?php
    $db = new mysqli('localhost', 'root' ,'', 'Technician');

    if(!$db) {

    echo 'Could not connect to the database.';
    } else {

    if(isset($_POST['queryString'])) {
    $queryString = $db->real_escape_string($_POST['queryString']);

    if(strlen($queryString) >0) {

    $query = $db->query("SELECT Tech_ID FROM tech WHERE Tech_ID LIKE '$queryString%' LIMIT 10");
    if($query) {
    echo '<ul>';
    while ($result = $query ->fetch_object()) {
    echo '<li onClick="fill(\''.addslashes($result->Tech_ID).'\');">'.$result->Internal_Tech_ID.'</li>';
    }
    echo '</ul>';

    } else {
    echo 'OOPS we had a problem ';
    }
    } else {
    // do nothing
    }
    } else {
    echo 'There should be no direct access to this script!';
    }
    }
    ?>

    The above code will fetch you the result from database for the tech number and now need to get the JOB number dropdw to be populated based on the selection from tech field....


    Please help me out..... If somebody has better code or another code please post it here.....

    Thanks

  2. #2
    Join Date
    May 2010
    Posts
    109
    I believe the best way to do this is, to build xml from the MySQL query result, echo the xml to the calling AJAX function, then parse the xml to build the select list.

    You sure don't need a framework to do it.

    Here's my code for a pro-forma example:

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>None</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    
    /*   AJAX/MySQL Dependent Select List */
    /*   Copyright 2008, Michael J. Hill.  Used with permission.  www.javascript-demos.com */
    /*   Free use of the code, so long as the above notice is kept intact */
    
    	function parseResponse(adminResponse,nList){
    
    		var nText = adminResponse.getElementsByTagName('optionText');
    		var nVal = adminResponse.getElementsByTagName('optionVal');
    		nList.options.length = 1;
    		for (i=0; i<nText.length; i++)
    			{ 
    			 var nOption = document.createElement('option'); 
    			 nOption.appendChild(document.createTextNode(nText[i].firstChild.data)); 
    			 nOption.value = nVal[i].firstChild.data; 
    			 nList.appendChild(nOption); 
    			}
    	}
    
    	function update(nVal,nList,getFile){
    
    		var adminRequest = window.XMLHttpRequest ? new XMLHttpRequest() 
    				 			 : window.ActiveXObject 
    				 			 ? new ActiveXObject("Microsoft.XMLHTTP") 
    				 			 : null;  
    		adminRequest.onreadystatechange = function()
    			{
    		 	 if (adminRequest.readyState == 4)
    				{
    		 	 	 if (adminRequest.status == 200)
    					{
    			 	 	 var adminResponse = adminRequest.responseXML;
    			 	 	 parseResponse(adminResponse,nList);
    					}
    		 	 	 else 	{
    				 	 alert('Error ' + getFile + ' --- ' + adminRequest.statusText);
    					}
    				}
    			}
    		var infoStr = "?choice="+nVal;
    		adminRequest.open("GET", getFile + infoStr, true);
    		adminRequest.send(null); 
    	}
    
    	function init(){
    
    		var nForm = document.forms[0];
    		nForm['foods'].onchange = function()
    			{
    			 if (this.value != "")
    				{
    			 	 update(this.value,nForm['group'],'updateGroup.php');
    				}
    			}		
    	}
    
    	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </script>
    <style type="text/css">
    
    	 body {background-color: #eae3c6; margin-top: 60px;}
    	 form {width: 430px; margin: auto;}
    	 fieldset {width: 410px; background-color: #f0fff0; border: 1px solid #87ceeb;}
    	 legend {font-family: times; font-size: 14pt; color: #00008b; background-color: #87ceeb;
    		 padding-left: 3px; padding-right: 3px ; margin-bottom:5px;}
    	 select {font-family: tahoma; font-size: 10pt; width: 160px; margin-left: 35px; margin-bottom: 10px;}	
    
    </style>
    </head>
    	<body>
    		<form action="">
    		   <fieldset>
    			<legend>Form</legend>
    				<select name="foods">
    					<option value=""> Choose a Food </option>
    					<option value="fruit"> Fruit </option>
    					<option value="vegetable"> Vegetable </option>
    				</select>
    				<select name="group" onchange="alert(this.value)">
    					<option value=""> Make a selection </option>
    				</select>
    		   </fieldset>
    		</form>
    	</body>
    </html>
    updateGroup.php:

    Code:
    <?php 
    
    	$choice = $_GET['choice'];
    	$xml = "<?xml version='1.0' ?><options>";
    
    	require_once('mySQL_connect.php');
    
    	$query = "SELECT * FROM categories WHERE food = '$choice'";
    	$result = @mysql_query($query);
    	$num = @mysql_num_rows($result);
    	if ($result && $num > 0)
    		{
    	 	 while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
    			{
    	 	 	 $xml .= "<optionText>" . $row['optText'] . "</optionText><optionVal>" . $row['optVal'] . "</optionVal>";
    			}
    		}
    	$xml .= "</options>";
    	@mysql_free_result($result);
    	@mysql_close();	
    	header("Content-Type: text/xml");
    	echo $xml;
    
    ?>

    table schema:

    Code:
    Table name: categories
    
    +---------+------------------+------+-----+---------+----------------+
    | Field   | Type             | Null | Key | Default | Extra          |
    +---------+------------------+------+-----+---------+----------------+
    | entry   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | food    | varchar(45)      | NO   |     |         |                |
    | optText | varchar(45)      | NO   |     |         |                |
    | optVal  | varchar(45)      | NO   |     |         |                |
    +---------+------------------+------+-----+---------+----------------+
    
    +-------+-----------+---------+--------+
    | entry | food      | optText | optVal |
    +-------+-----------+---------+--------+
    |     1 | fruit     | Apple   | f1     |
    |     2 | fruit     | Banana  | f2     |
    |     3 | fruit     | Orange  | f3     |
    |     4 | vegetable | Celery  | v1     |
    |     5 | vegetable | Onion   | v2     |
    |     6 | vegetable | Lettuce | v3     |
    +-------+-----------+---------+--------+

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles