简体   繁体   中英

PHP - Updating values in drop down list upon user input

I have got 2 drop down list in my php form. Values in the drop down list would be retrieved from the database(mysql). I have got the first drop down list running. But now I need to update the 2nd drop down list upon the user's selection. The value displayed in the 2nd drop down would defer depending on the user's selection.

How do I update values of another drop down list after a user has selected an option from the first drop down list? I have searched and seen similar question on SO but they aren't answered. Hope to get some help here. Thanks. Below is my current code I have.

PS. If I were to create a html form, I would need to run the php script upon lauching, without any inputs to populate the first drop down list. How do I so? I'm only aware of how to send request upon inputs; Eg <input type=submit>

.php

<?php
$conn = mysql_connect("127.0.0.1","root","")
mysql_select_db(MyApp,$conn);


$sql2=("SELECT App.AppName FROM App);               


$result2=mysql_query($sql2); 
echo '<select name="sublist">';
echo '<option value=""></option>';

while ($row2 = mysql_fetch_assoc($result2))
{
    echo '<option value="' . $row2['AppName'] . '">' . $row2['AppName']. '</option>';
}
echo '</select>';                                           
?>

You have two solutions for this.

  1. Do completely in PHP (I do not recommend since, it's not much user friendly)
  2. Ajax based (More user friendly)

However to perform both things in good manner you need support of Javascript

So if I explain you the solution one. Once user change your first dropdown list. You have to POST your page to the same page using onChange() event. Then in your page set the elements for the second dropdown list same as you did for the first dropdown.

The second solution require AJAX. Once user change the first dropdown you make a AJAX request to a page. In that page you catch the selection user did. And you generate the second dropdown based on that. Here you can use three methods to get the second dropdown or it's data.

a. You generate the all the options from that page and send back. Set the innerHTML of the second dropdown.

b. Get the data as JSON and populate your dropdown based on that.

c. Get AJAX XML and populate your dropdown based on that.

there's more than one way to do this:

1) have a request sent to the server with the user selection, retrieve the contents of the second select box and display it. This can also be done in two ways a) AJAX -- so the page isn't refreshed (smooth user experience) b) refresh the whole page -- (simpler to implement)

2) load all the combinations and then upon the user's selection, show the specific drop-down. This is only feasible (in terms of not generating large pages) if you have small drop-downs with few combinations.

As noted by another poster , all methods need JavaScript (to some extent) to run. Please detail which approach is desirable and i'll go in further detail

View source to copy the code. JQuery has a way of making this simple. I used a form creator that I custom made. But here is the output - the manual way.

Here is your ajax file. It goes in a JS or the header.

    function getXMLObject()  //XML OBJECT
    {
       var xmlHttp = false;
       try {
         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
       }
       catch (e) {
         try {
           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
         }
         catch (e2) {
           xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
         }
       }
       if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
         xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
       }
       return xmlHttp;  // Mandatory Statement returning the ajax object created
    }

    var xmlhttp = new getXMLObject();   //xmlhttp holds the ajax object

    function makeAjaxRequest(url, params, output, image) {
      var getdate = new Date();  //Used to prevent caching during ajax call
      if( image == 1 ){
          document.getElementById(output).innerHTML='<img src="./images/template/ajax-loader.gif"></img>'; 
      }
      if(xmlhttp) { 
        xmlhttp.open("POST",url,true); //calling testing.php using POST method
        xmlhttp.onreadystatechange = function(){
           if (xmlhttp.readyState == 4) {
             if(xmlhttp.status == 200) {
               document.getElementById(output).innerHTML=xmlhttp.responseText; //Update the HTML Form element 
             }
             else {
    //          alert("Error during AJAX call. Please try again");
             }
           }    
        }
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send(params); //Posting txtname to PHP File
      }
    }

    function makeAjaxGetRequest(url, output, image) {
      var getdate = new Date();  //Used to prevent caching during ajax call
      if( image == 1 ){
          document.getElementById(output).innerHTML='<img src="./images/template/ajax-loader.gif"></img>'; 
      }
      if(xmlhttp) { 
        xmlhttp.open("GET",url,true); //calling testing.php using GET method
        xmlhttp.onreadystatechange = function(){
           if (xmlhttp.readyState == 4) {
             if(xmlhttp.status == 200) {
               document.getElementById(output).innerHTML=xmlhttp.responseText; //Update the HTML Form element 
             }
             else {
    //          alert("Error during AJAX call. Please try again.");
             }
           }    
        }
        xmlhttp.send(null); //Posting txtname to PHP File
      }
    }

    function emptyAjaxReportBox(id)
    {
        document.getElementById(id).innerHTML= '';
    }

Here is the file that the user navigates to:

// your call file; what you posted above.  Obviously change the names and Id's to match what you need.
<form  id="testFormId"  name="testForm"  action="post" >
<select  id="firstSelectId"  name="firstSelect"  onchange="makeAjaxRequest('url', 'firstSelect='+encodeURIComponent(document.getElementById('firstSelectId').value),'outputDivId', '0');" >
</select>
<div  id="outputDivId" >
<select name="secondInput">Whatever values you want to load up can go in here.  They can be the default values; meaning, if select 1 value = 0, then you have have these values in select 2.  Once you change select 1, this will disappear and be replaced by what your ajax returns.  Therefore, for easy processing after you submit the form, you should make this select 2 the same name and id as what you use in the ajax.</div>
</form>

Here is the file that is called upon the ajax request.

//your AJAX file needs to be a separate page than what you're currently reading.  Put whatever you want in there.
$db = connectioninfo;
$query;
echo 'What you put in the echo is what will show up in the outputDiv.  <select></select>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM