Dynamic/Chained Selects using Ajax Prototype/JQuery

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Is this useful to you

Yes
7
64%
No
1
9%
Would be if you added... (Please post suggestions)
3
27%
 
Total votes: 11

User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

The way I do it in IJ is (roughly):

Requesting a project calls AJAXTaskProjectsSelectRequest(project_id) ... that rebuilds the projects dropdown (id of 'viewTaskProject'). It's slightly messy to cascade through 3 functions, but it works within the application design.

Code: Select all

function AJAXTaskProjectsSelectRequest(project_id) {

	var url = 'ajax/get_project_select.php?projectsIdSelected='+project_id;
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get',
			onSuccess   : AJAXTaskProjectsSelect,
			onException : onExceptionRequest,
			onFailure   : onFailureRequest
		});

}

function AJAXTaskProjectsSelect(xhr, json) {

	var selected = json.projectsIdSelected;
	var options = json.projectsArray;
	rebuildSelect('viewTaskProject',selected,options);

}

function rebuildSelect(selectElementId, selectedId, optionsArray) {

	var selectElement = document.getElementById(selectElementId);
	
	while(selectElement.hasChildNodes() == true) {	
		selectElement.removeChild(selectElement.childNodes[0]);
		
	}
	
	if (optionsArray.length>0) {
		for (var h=0; h < optionsArray.length; h++) {

			newOption = document.createElement("option");
			newOption.value = optionsArray[h].id;
			if (optionsArray[h].id == selectedId) { newOption.selected = true; }
			newOption.appendChild(document.createTextNode(optionsArray[h].title));

			selectElement.appendChild(newOption);

		}
	}

}
get_project_select.php returns an array in JSON format...

Code: Select all

<?php

	include_once("../includes/constants.inc.php");

	$sql  = "select ";
	$sql .= "* ";
	$sql .= "from ";
	$sql .= "int_project ";
	$sql .= "where 1 ";
	$sql .= "order by title asc ";
	$result = mysql_query($sql,$databaseLink);

	$jsonFields[] .= "\"totalProjects\" : ".mysql_num_rows($result);
	$jsonFields[] .= "\"projectsIdSelected\" : ".$_GET['projectsIdSelected'];

	if (mysql_num_rows($result) > 0) {
		while ($record = mysql_fetch_object($result)) {
			$projects[] = "{ \"id\" : \"".$record->project_id."\", \"title\" : \"".$record->title." (".$record->client_id.")\" }";
		}
	} else {
		$projects[] = "{ \"title\" : \"No projects found\", \"id\" : \"\" }";
	}
	
	$jsonFields[] = "\"projectsArray\" : [".implode(", ",$projects)." ]";

	$jsonText = "{ ".implode(", ",$jsonFields)." }";

	header("Cache-Control: no-store, no-cache, must-revalidate");
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache");

	header("X-JSON: $jsonText");
	
	echo $jsonText;

?>
The rebuildSelect() function is what does most of the actual work.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I forget where I read this, but innerHTML is orders of magnitude faster than the proper w3c method. There's apparently quite a petition already to have it added to the spec.

I'm of the opinion that once you understand and obey the idea behind the law, you can ignore the letter of the law. This may be one of those times.
prakashadmane
Forum Commoner
Posts: 33
Joined: Thu Mar 01, 2007 1:53 am
Location: mumbai,india
Contact:

Re: Dynamic/Chained Selects using Ajax Prototype/JQuery

Post by prakashadmane »

Country:
<select name=country>
<option value=1>U.S.A</option>
.
.
.
</select>



City: <select name=city>


<option value=1>New York</option>
.
.
.
</select>



State: <select name=state>


<option value=1>XXX</option>
.
.
.
</select>

When user change country then automatically comes reletad city & sate come from database with respect to country . how will be implement using ajax & php ? plz help me
Last edited by prakashadmane on Wed Oct 26, 2022 6:50 am, edited 1 time in total.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Dynamic/Chained Selects using Ajax Prototype/JQuery

Post by onion2k »

prakashadmane wrote:how will be implement using ajax & php ?
Read the code posted so far, it'll do exactly what you're looking for.
prakashadmane
Forum Commoner
Posts: 33
Joined: Thu Mar 01, 2007 1:53 am
Location: mumbai,india
Contact:

Re: Dynamic/Chained Selects using Ajax Prototype/JQuery

Post by prakashadmane »

onion2k wrote:
prakashadmane wrote:how will be implement using ajax & php ?
Read the code posted so far, it'll do exactly what you're looking for.




which code plz tell me ???
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Dynamic/Chained Selects using Ajax Prototype/JQuery

Post by onion2k »

prakashadmane wrote:which code plz tell me ???
The code in the first post of this thread. Or any of the replies.
prakashadmane
Forum Commoner
Posts: 33
Joined: Thu Mar 01, 2007 1:53 am
Location: mumbai,india
Contact:

Re: Dynamic/Chained Selects using Ajax Prototype/JQuery

Post by prakashadmane »

onion2k wrote:
prakashadmane wrote:which code plz tell me ???
The code in the first post of this thread. Or any of the replies.


plz send me file to complte these code

<script src="prototype.js" type="text/javascript"></script>
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Dynamic/Chained Selects using Ajax Prototype/JQuery

Post by onion2k »

prakashadmane wrote:plz send me file to complte these code
<script src="prototype.js" type="text/javascript"></script>
If you want someone to write this code for you, as it appears you do, please start a thread in either the Volunteers or Jobs forum.

Also, AOL speak is against the rules of the forum, so stop saying "plz".
devil78
Forum Newbie
Posts: 7
Joined: Wed Aug 22, 2007 1:08 pm

Post by devil78 »

Hi to all!

I really like the code developed by CoderGoblin... but a question. I'd like to submit data when user choice the last select. How i can do it?

i try to modify the script but without luck :D

Thanks
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Try the following as an example (uses prototype adjust accordingly) to get an idea of how to do it. Obviously the final mechanics are for you to determine, especially in regards to if the second combo box is pre filled in. Maybe you need to add an 'Please Select' if you do not have an existing value.. Also sorry to say haven't had time to fully test.
index.php

Code: Select all

<?php
  // $value will be available during the include of sublist.php
 $value=0;
 if (!empty($_GET['second'])) $changed='Changed ... Validate and Redirect ?';
 if (!empty($_GET['sublist'])) {
    $value=floor($_GET['first']);
    if ($_GET['sublist'] == 'Find...') $changed=''; // Check if we do actually have a change if no JS is used.
 }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <script src="prototype.js" type="text/javascript"></script>
 <script type="text/javascript">
  function getSecond(value) {
    var url = 'sublist.php';
    var myAjax = new Ajax.Request
      (
        url,
        {
          method: "post",
          parameters : "first="+value,           
          onSuccess: function transResult (response) {
            document.getElementById('sublist').innerHTML=response.responseText;
            document.getElementById('doneit').innerHTML='';                       
          },
          onFailure: function transResult (response) {
            alert ('Failure'+response.responseText);
          }
        }
      );
      return false;
  }
  </script>
</head>
<body>
  <form name="myform">
    <span id="firstlist">
      <select name="first" onchange="getSecond(this.value);">
        <option value="1" <?php if ($value==1) echo " selected"; ?> >Names starting with A</option>
        <option value="2" <?php if ($value==2) echo " selected"; ?> >Names starting with B</option>
        <option value="3" <?php if ($value==3) echo " selected"; ?> >Names starting with C</option>
        <option value="4" <?php if ($value==4) echo " selected"; ?> >Names starting with D</option>
        <option value="5" <?php if ($value==5) echo " selected"; ?> >Names starting with E</option>     
      </select>
    </span>
   
    <!-- This is for those with no javascript -->
    <noscript><input type="submit" name="sublist" value="Find..." /></noscript>
 
    <span id="sublist"><?php include 'sublist.php'; ?></span>
  </form>
  <p id="doneit" style="color:green; text-align:center;"><?php echo $changed; ?></p>
  <noscript><br />This page is enhanced by javascript which is currently not available</noscript>
</body>
</html>
sublist.php

Code: Select all

<?php
// Define the result list possibilities. This could easily be retrieved from a database
$blank='Please Select...';
$sublist=array(1=>array(1=>'Anna',2=>'Andrew',3=>'Andrea',4=>'Annakin'),
               2=>array(1=>'Bill',2=>'Bob',3=>'Bernie'),
               3=>array(1=>'Charles',2=>'Camila',3=>'Connie',4=>'Constance'),
               4=>array(1=>'Daniel',2=>'Darla',3=>'Danny'),
               5=>array(1=>'Edmund',2=>'Edgar',3=>'Elisabeth',4=>'Eugene',5=>'Emma',6=>'Emily'));

// Process
if (empty($value)) $value=1;
if (!empty($_POST['first'])) {
    if (isset($sublist[$_POST['first']])) $value=$_POST['first'];
}

$name_list='';
foreach ($sublist[$value] as $key=>$name) {
    $name_list.="<option value=\"{$key}\">{$name}</option>\n";
}
echo <<<EOBLOCK
<select name="second" onchange="document.myform.submit();">{$name_list}</select>
<!-- This is for those with no javascript -->
<noscript><input type="submit" name="sublist" value="end..." /></noscript>
EOBLOCK;

?>
devil78
Forum Newbie
Posts: 7
Joined: Wed Aug 22, 2007 1:08 pm

Post by devil78 »

Thank you very much, with your suggests i found my solution! Grazie! :D
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

OK this topic is getting quite long now and a lot of information requested is not to do with the original baseline code but more of "enhancements". As such if you need additional help on this topic please open a new topic (in PHP Code) referencing this topic with the additional query. Thanks for your understanding in this matter.

CoderGoblin
davidtube
Forum Commoner
Posts: 79
Joined: Sun Mar 25, 2007 8:42 pm

Post by davidtube »

This has been very useful for me. Thank you.

I have a bit of a problem though. I've changed the code so the listboxes are populated from a database, and it seems to work but I have an error message when the page first loads. After selecting an option the error message vanishes. The error message I get is "Warning: Invalid argument supplied for foreach()

You can see how the code works here and which parts I've changed. Does anyone know what's wrong with the foreach loop?

Code: Select all

$otherslist=mysql_query("SELECT subcat FROM subcat WHERE catagory='Others' ORDER BY subcat");
while ($row = mysql_fetch_assoc($otherslist)) {
   $others[] = $row['subcat'];
}

$sublist=array('Games'=>$games,
               'Electronics'=>$electronics,
               'DVDs'=>$dvd,
               'Music'=>$music,
               'Others'=>$others);



// Here to the end of the code remains as in the original example


$value=1;
if (!empty($_POST['first'])) {
    if (isset($sublist[$_POST['first']])) $value=$_POST['first'];
}
$name_list='';


// The error message I get is "Warning: Invalid argument supplied for foreach()"


foreach ($sublist[$value] as $name) {
    $name_list.="<option value=\"{$name}\">{$name}</option>\n";
}
echo '<select name="second">'.$name_list.'</select>';
?>
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

I will no longer answer questions of the nature "can't get my modified code to work..." on this topic. Please ask your questions by opening a new topic in the PHP Code Section and reference this one.

To be nice this time however... davidtube Answer
Post Reply