-2

I have two dropdown lists. Both are to be filled by PHP via a mysql query. My problem is I want the form to be responsive if these list selections change. For instance, I need to populate the second list via another query based upon the selection of the first list.

Problem is: I need "on_change" to POST the form data AND to trigger PHP instead of Javascript. Is there a way to collect that selection in Javascript and then send it to PHP and then refill the form? Hope I'm making myself clear. Thanks,

Dana

Dana White
  • 41
  • 4
  • 1
    You are pretty much describing AJAX, http://stackoverflow.com/questions/1510011/how-does-ajax-work – Rick Smith Jun 10 '15 at 18:58
  • 1
    There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.I would suggest that you find a development forum (perhaps [quora](http://www.quora.com/Computer-Programming)?) to work out generalities. Then, when you have specific coding issues, come back to StackOverflow and we'll be glad to help. – Jay Blanchard Jun 10 '15 at 19:00
  • @DanaWhite, you can do it with traditional forms : when one combo is selected, you send the form with the selected value, PHP responds, and the page refreshes with the first combo autoselected and the second combo with different options. Or you can use Ajax as the other suggest. – Jose Manuel Abarca Rodríguez Jun 10 '15 at 19:06
  • I'm already still new to much of this. I'll try your suggestion, Mr. Rodriquez. Thank you very much. I was unaware I could 'send' a form when a value was selected. I'll look into that. – Dana White Jun 10 '15 at 23:44

5 Answers5

1

Use Javascript to detect a change of the list. When a change occurs, you can make an AJAX request using a PHP script to return a new list. Javascript can manipulate the new data set and replace the DOM with the new appropriate list.

Kirk Powell
  • 908
  • 9
  • 14
0
<script type=\"text/javascript\">
            function changeCountry(){
                var e = document.getElementById(\"country_id\");
                var country_id = e.options[e.selectedIndex].value;
                if(country_id == 1){
                    // Display states
                    document.getElementById('display_province').style.display = \"none\";
                    document.getElementById('display_state').style.display = \"\";
                    document.getElementById('display_state').style.visibility = \"visible\";
                }
                else{
                    // Display Province
                    document.getElementById('display_state').style.display = \"none\";
                    document.getElementById('display_province').style.display = \"\";
                    document.getElementById('display_province').style.visibility = \"visible\";
                    // Remove current selection list 
                    var select = document.getElementById('province_id');
                    for (var option in select){
                        select.remove(option);
                    }
                    // Get Provinces for country_id
                    var xmlhttp = new XMLHttpRequest();
                    // Include fix for IE6 and IE5
                    if (window.XMLHttpRequest) {
                        // code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp = new XMLHttpRequest();
                    } else {
                        // code for IE6, IE5
                        xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                    }
                    xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            var xmlDoc = xmlhttp.responseXML;
                            // get each property
                            var x=xmlDoc.getElementsByTagName('province');
                            for (i=0;i<x.length;i++)
                            { 
                                var e = document.getElementById('province_id');
                                var opt = document.createElement('option');
                                opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
                                opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
                                e.appendChild(opt);
                            }
                        }
                    }
                    var url = 'get_provinces.php?country_id='+country_id;
                    // var url = 'provinces.xml';
                    xmlhttp.open('GET',url,false);
                    xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                    xmlhttp.send();
                }
            }
            function changeShippingCountry(){
                var e = document.getElementById(\"shipto_country_id\");
                var shipto_country_id = e.options[e.selectedIndex].value;
                if(shipto_country_id == 1){
                    // Display states
                    document.getElementById('shipto_display_province').style.display = \"none\";
                    document.getElementById('shipto_display_state').style.display = \"\";
                    document.getElementById('shipto_display_state').style.visibility = \"visible\";
                }
                else{
                    // Display Province
                    document.getElementById('shipto_display_state').style.display = \"none\";
                    document.getElementById('shipto_display_province').style.display = \"\";
                    document.getElementById('shipto_display_province').style.visibility = \"visible\";
                    // Remove current selection list 
                    var select = document.getElementById('shipto_province_id');
                    for (var option in select){
                        select.remove(option);
                    }
                    // Get Provinces for country_id
                    var xmlhttp = new XMLHttpRequest();
                    // Include fix for IE6 and IE5
                    if (window.XMLHttpRequest) {
                        // code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp = new XMLHttpRequest();
                    } else {
                        // code for IE6, IE5
                        xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                    }
                    xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            var xmlDoc = xmlhttp.responseXML;
                            // get each property
                            var x=xmlDoc.getElementsByTagName('province');
                            for (i=0;i<x.length;i++)
                            { 
                                var e = document.getElementById('shipto_province_id');
                                var opt = document.createElement('option');
                                opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
                                opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
                                e.appendChild(opt);
                            }
                        }
                    }
                    var url = 'get_provinces.php?country_id='+shipto_country_id;
                    // var url = 'provinces.xml';
                    xmlhttp.open('GET',url,false);
                    xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                    xmlhttp.send();
                }
            }
            function addProvince(){
                // Get input
                var np = document.getElementById('new_province').value;
                // Get country_id
                var e = document.getElementById(\"country_id\");
                var country_id = e.options[e.selectedIndex].value;
                // Erase input
                document.getElementById('new_province').value = \"\";
                // Add to database
                var xmlhttp = new XMLHttpRequest();
                // Include fix for IE6 and IE5
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var xmlDoc = xmlhttp.responseXML;
                    }
                }
                var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
                xmlhttp.open('GET',url,false);
                xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                xmlhttp.send();
                changeCountry();
                changeShippingCountry();
            }
            function addShippingProvince(){
                // Get input
                var np = document.getElementById('shipto_new_province').value;
                // Get country_id
                var e = document.getElementById(\"shipto_country_id\");
                var country_id = e.options[e.selectedIndex].value;
                // Erase input
                document.getElementById('shipto_new_province').value = \"\";
                // Add to database
                var xmlhttp = new XMLHttpRequest();
                // Include fix for IE6 and IE5
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var xmlDoc = xmlhttp.responseXML;
                    }
                }
                var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
                xmlhttp.open('GET',url,false);
                xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                xmlhttp.send();
                changeShippingCountry();
                changeCountry();                
            }
            function hideShipping(){
                    document.getElementById('shipping').style.display = \"none\";
                    document.getElementById('shipping').style.visibility = \"hidden\";
            }
            function displayShipping(){
                    document.getElementById('shipping').style.display = \"\";
                    document.getElementById('shipping').style.visibility = \"visible\";
            }
Kirk Powell
  • 908
  • 9
  • 14
  • Don't you just want to edit your original answer? How did you come up with all of this code for such a broad question? And why haven't you added an explanation for what you did? – Jay Blanchard Jun 10 '15 at 19:32
  • This is code I wrote to do the exact problem that was asked. The Javascript was the pertinent answer to the question. For some reason, when I try to post code along with text, my browser has been creating errors. I'm in the middle of a C# tutorial, so I am beholden to the environment. – Kirk Powell Jun 10 '15 at 19:35
0

You can make an ajax call to an endpoint you set up that runs some php code and returns some JSON that your javascript can then use to populate the second list. Your javascript would look something like:

$.ajax( "your-endpoint.php" )
  .done(function(data) {
    // use javascript to dynamically populate your list
    var json = data;
    //assuming data is a list you could iterate over it
    $.each(data, function (k, v) {
      //use this to populate your list
    }
  })
  .fail(function() {
    // show an error message on your form
  });

Your PHP endpoint would have to return a JSON object so that your javascript can more easily use it.

Leo Bauza
  • 275
  • 1
  • 8
0

Communcation betwen php and javascript is typically done by Ajax, which is very simple to use in jQuery. The basic syntax is something like this:

$.ajax({
    type: "POST",
    url: "yourFile.php",
    data: "{data: " + yourData + "}", //yourData is javascript variable 
    success: function(result){
        //do something with result from php file
    }
});

Where variable yourData is what you want to send to php script and it would be accessible throught $_POST['data'].

Pavel Němec
  • 272
  • 1
  • 5
  • 16
0

Everyone answered that Ajax is the solution, and I agree, Ajax is more elegant, but Ajax is not the only solution. I post this answer only to show another way to do it : without Ajax.

The first code (combos.php) is the page with a combo that, when selected, calls PHP. The second code (combos_action.php) is the PHP that returns the values according to the option selected. To make this codes to work, create two text files with the given names, copy-paste the codes and run it from your browser with http://localhost/combos.php. If you change the filenames, change them in the code, also.

Here is how it works : the page shows a simple combo filled with the days of the week. When a day is selected the JavaScript's onchange event fires and the form is autosubmitted, PHP gets the selected day and stores some values in session, returns to the page that refreshes and fills the second combo with those values. Comments will help you to understand:

combos.php

<?php
session_start(); // NECESSARY TO RETRIEVE THE VALUE RETURNED FROM PHP.
?>
<html>
  <head>
    <title>By José Manuel Abarca Rodríguez</title>
    <script type="text/javascript">

// AUTOSUBMIT FORM #1 WHEN ANY OPTION IN COMBO #1 IS SELECTED.
function combo1_selected () {
document.getElementById( "form1" ).submit();
}
    </script>
  </head>
  <body>
<!-- THIS IS COMBO #1. -->
    <form id="form1" method="post" action="combos_action.php">
      Select a day
      <br/>
      <select name="combo1" onchange="combo1_selected()"> <!-- NOTICE THE EVENT! -->
        <option>Monday</option>
        <option>Tuesday</option>
        <option>Wednesday</option>
      </select>
    </form>
<?php
// DISPLAY COMBO #2 ONLY IF COMBO #1 WAS SELECTED.
if ( isset( $_SESSION[ "combo2" ] ) )
   { echo "<br/>" .
          "<br/>" .
          "Options for <b>" . $_SESSION[ "combo1" ] . "</b>" .
          "<br/>" .
          "<select name='combo2'>";
     // SEPARATE THE OPTIONS RETURNED FROM PHP.
       $options = explode( ",",$_SESSION[ "combo2" ] );
     // DISPLAY THE OPTIONS FOR THE COMBO.
       for ( $i = 0; $i < count( $options ); $i++ )
         echo "<option>" . $options[ $i ] . "</option>";
     echo "</select>";
   }
?>
  </body>
</html>

combos_action.php

<?php
session_start();
$_SESSION[ "combo1" ] = $_POST[ "combo1" ]; // SELECTED OPTION.

if ( $_SESSION[ "combo1" ] == "Monday" )
   $_SESSION[ "combo2" ] = "mon 1,mon 2,mon 3"; // RETURN THESE VALUES.

if ( $_SESSION[ "combo1" ] == "Tuesday" )
   $_SESSION[ "combo2" ] = "tue 1,tue 2,tue 3"; // RETURN THESE VALUES.

if ( $_SESSION[ "combo1" ] == "Wednesday" )
   $_SESSION[ "combo2" ] = "wed 1,wed 2,wed 3"; // RETURN THESE VALUES.

header( "Location: combos.php" ); // RETURN TO PAGE.
?>