Link to home
Start Free TrialLog in
Avatar of dannyg280
dannyg280Flag for United States of America

asked on

How to create php variable from the selected value of a dropdown.

I have a form in which the user enters a description, chooses a category from the dropdown. I then want the the sub category dropdown to populate with with sub categories for the selected category. Because the categories change from time to time I am pulling the values from my database. The code I have is below but I don't know how to get the selected value from the Category dropdown into $catcode variable.

<form action="php/addmachine.php">
<label for="m_desc">Machine Description</label>
<input name="m_desc" type="text" id="m_desc" maxlength="60">
<div data-role="fieldcontain">
	<label for="catselect" class="Catselect">Choose Category:</label>
    <select name="catselect" id="Category">
       <?   
	   include("db.php");
 $mysqli = new mysqli("$host", "$username", "$password", "$db_name");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();

}
else {
          $result=$mysqli->query("SELECT DISTINCT GroupCode, GroupName FROM mgroups Order by GroupName Asc");

    while($row3=$result->fetch_array())
    	{
        echo"<option value='".$row3['GroupCode']."'>".$row3['GroupName']."</option>"; 
    	}
}
	?>
          
          </select>
        </div>

      </div>


<div data-role="fieldcontain">
          <label for="subcatselect" class="select">Choose Sub-Category: <? echo $catcode ?></label>
          <select name="subcatselect" id="Category">
       <?  
          $result=$mysqli->query("SELECT DISTINCT SubGroupCode, SubGroupName FROM mgroups Where GroupCode = '$catcode' Order by SubGroupName Asc");

    while($row4=$result->fetch_array())
    {
        echo"<option value='".$row4['SubGroupCode']."'>".$row4['SubGroupName']."</option>"; 
    }
	?>
          
          </select>
</div>
</form>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

I think the thing you want is called a "dependent dropdown."  There are jQuery plugins that can help with this, using AJAX calls to query the server.

At the heart of this, you will need to understand client/server protocols.  When the web page is presented, the (human) client will use a set of HTML controls to make an initial selection.  This selection will be used in an AJAX request to the server.  The server will respond with some data (probably JSON format) and the client browser will use this response data to create the second set of select options.

You can simplify the development process if you do it in this order, using GET-method requests.

1. Develop the PHP script for second set of select options.  It will receive a GET request with the "catcode" and will respond with the JSON string for the options list.

2. Develop the JavaScript that takes the JSON string and creates the select options

3. Develop the AJAX call last.

If you do it in this order, most of your debugging can be done from the browser address bar.
Avatar of hielo
Submit an ajax request that sends the selected Category.  Once you detect the ajax request, use the Category to query the db for the Sub Category.  When you receive the result, update your list -- see below:
<?php
 include("db.php");
 $mysqli = new mysqli("$host", "$username", "$password", "$db_name");

	// this if clause is executed when this script receives an ajax request
	if( array_key_exists('ajax-request',$_POST) )
	{
		$catcode = $_POST['catselect'];
		
	    $result=$mysqli->query("SELECT DISTINCT SubGroupCode, SubGroupName FROM mgroups Where GroupCode = '$catcode' Order by SubGroupName Asc");
		
		$data=Array('Category'=>$catselect, 'options'=>'');
		
		while($row4=$result->fetch_array())
		{
			$data['options'].="<option value='".$row4['SubGroupCode']."'>".$row4['SubGroupName']."</option>"; 
		}
		$result=null;
		
		echo json_encode($data);
		
		exit;
	}
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
	$('#myForm').on('change','#Category',function(){
		$.ajax({	method: "POST",
					url: $('#myForm').attr('action'),
					data: { 'catselect': $('#Category').val(), 'ajax-request':true }
			})
			.done(function( json_msg ) {
				$('#selected_category').text(json_msg.Category);
				$(json_msg.options).appendTo('#SubCategory');
			});
	});
})
</script>

<form id="myForm" action="php/addmachine.php">
<label for="m_desc">Machine Description</label>
<input name="m_desc" type="text" id="m_desc" maxlength="60">
<div data-role="fieldcontain">
	<label for="catselect" class="Catselect">Choose Category:</label>
    <select name="catselect" id="Category">
       <?php   
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();

}
else {
          $result=$mysqli->query("SELECT DISTINCT GroupCode, GroupName FROM mgroups Order by GroupName Asc");

    while($row3=$result->fetch_array())
    	{
        echo"<option value='".$row3['GroupCode']."'>".$row3['GroupName']."</option>"; 
    	}
}
	?>
          
          </select>
        </div>

      </div>


<div data-role="fieldcontain">
          <label for="subcatselect" class="select">Choose Sub-Category: <span id="selected_category"></span></label>
          <select name="subcatselect" id="SubCategory"></select>
</div>
</form>

Open in new window

Avatar of dannyg280

ASKER

Thank you for the responses. heleo I think I get what you're trying to show me here. myForm has an action of  addmachine.php  which is a separate script which adds the form details to my database. It appears from the code you gave me that the JS function is posting to that script, which wasn't my intent. I had not yet included a submit button on the bottom but my intent was to submit the data to addmachine.php after the form had been completely filled out.
>> which is a separate script which adds the form details to my database
OK

>> it appears from the code you gave me that the JS function is posting to that script
Yes.  So, from what I posted, you can put the following at the start of "addmachine.php" and the sub-selection should work:
<?php
 include("db.php");
 $mysqli = new mysqli("$host", "$username", "$password", "$db_name");

	// this if clause is executed when this script receives an ajax request
	if( array_key_exists('ajax-request',$_POST) )
	{
		$catcode = $_POST['catselect'];
		
	    $result=$mysqli->query("SELECT DISTINCT SubGroupCode, SubGroupName FROM mgroups Where GroupCode = '$catcode' Order by SubGroupName Asc");
		
		$data=Array('Category'=>$catselect, 'options'=>'');
		
		while($row4=$result->fetch_array())
		{
			$data['options'].="<option value='".$row4['SubGroupCode']."'>".$row4['SubGroupName']."</option>"; 
		}
		$result=null;
		
		echo json_encode($data);
		
		exit;
	}
?>

Open in new window

The code above would only work if it sees $_POST['ajax-request'].  Since your form does not have any field that matches that name(ex: <input type="text" name="ajax-request"/>), the "block" of code will get skipped when you actually submit your <form> (I'm guessing by pressing some "Submit" button).
Thanks again for the response:
     Everything seems to work correctly but the 2nd select box was still not updating. When I look at the HTML response after the POST I see
{"Category":null,"options":"<option value='AdvBuff'>Advance Floor Buffer<\/option><option value='CORBuff'
>COR Floor Buffer<\/option><option value='UnknownBuff'>Other Brand\/Unknown Buffer<\/option><option value
='TasBuff'>Taski Floor Buffer<\/option><option value='TenBuff'>Tennant Floor Buffer<\/option><option
 value='WinBuff'>Windsor Floor Buffer<\/option>"}

Open in new window


So it's definitely passing the category via POST and the query is running successfully but it appears the output is not formatted correctly?
Are you sure you are appending just the "options" sub-key of the result?  It looks like you are appending the entire result.  Add the dataType option to the ajax call (see below), and make sure that you are appending just the "options" sub-key:
$.ajax({      method: "POST",
                              url: $('#myForm').attr('action'),
                                        dataType:'json',
                              data: { 'catselect': $('#Category').val(), 'ajax-request':true }
                  })
                  .done(function( json_msg ) {
                        $('#selected_category').text(json_msg.Category);
                        $(json_msg.options).appendTo('#SubCategory');
                  });

Also, on the server script add a header() call as shown below:
            $result=null;
                header('Content-Type: application/json');            
            echo json_encode($data);
            
            exit;
I've requested that this question be closed as follows:

Accepted answer: 167 points for hielo's comment #a40895956
Assisted answer: 167 points for hielo's comment #a40893639
Assisted answer: 166 points for hielo's comment #a40894037
Assisted answer: 0 points for dannyg280's comment #a40895167

for the following reason:

Thank you for your patience, it works perfectly now.
hielo - One last issue... If the user changes the Category drop down after selecting a category, the subcat drop-down now contains sub cats from both the current AND previously selected category. I assume I just need to add a line to On Change function...
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial