2

I have a web page that includes 3 dropdown list that includes data retrieved from MYSQL database.

I want to make these three dropdown list dependent on each other where the user select from the first dropdownlist and based on the user's selection the second dropdown list display the data related to the first dropdown and the same thing happen between the second and the third dropdownlist.

i wrote a code but nothing is happen where is my error and how to fix it ??

javascript code:

<script type="text/javascript">

// make Dropdownlist depend on each other
$(document).ready(function(){
  $('#site_name').on('change'function(){
    var SITENAME = $(this).val();

   if(SITENAME){
    $.ajax({
     url: 'search_info_location.php',
     type:'POST',
     data:'site_name='+SITENAME,
     dataType: 'json',
     success:function(html){

        $('#owner_name').html(html);
        $('#Company_name').html('<option value="">Select Owner Name</option>');
     }

    });
   }
   else{
      $('#owner_name').html('<option value="">Select Site Name first</option>');
      $('#Company_name').html('<option value="">Select Owner Name first</option>'); 
   }
  });

  $('#owner_name').on('change',function(){
     var OWNERNAME = $(this).val();
     if(OWNERNAME){
        $.ajax({
           type:'POST',
           url:'search_info_location.php',
           data:'owner_name='+OWNERNAME,
           success:function(html){
             $('#Company_name').html(html);
           }

        });
     }else{
        $('#Company_name').html('<option value="">Select Owner Name first</option>');
     }

  });

});

Note: i am extracting the data from database as object than i converted to json object , using json_encode()

completed code:

   <?php
        /*
        Template Name: search info_location
        */

        get_header();
          ?>

<!DOCTYPE html>
<html>
  <head>
    <title>Custom Markers</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <script src="jquery.min.js"></script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCquey2tCZ32jLJJDEEi2D7_RnXXyj9RTI&callback=initMap">
    </script>
     <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 400px;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

    </style>

  </head>
  <body>
    <div id="map"></div>


  <?php
        // code for submit button action
        global $wpdb, $site_name;
    //variables that handle the retrieved data from mysql database based on the ID of the variable in HTML (select)



    if(isset($_POST['query_submit']))
    {


       if(isset($_POST['site_name'])) 
          { 
           $site_name=$_POST['site_name'];

          }
          else { $site_name=""; }


        if(isset($_POST['owner_name'])) 
         {
          $owner_name=$_POST['owner_name']; 

         } 
         else { $owner_name=""; }

         if(isset($_POST['Company_name'])) 
         {
          $company_name=$_POST['Company_name'];

         } 
         else { $company_name=""; }

        if(isset($_POST['Subcontractor_name'])) 
        { 
         $Subcontractor_name=$_POST['Subcontractor_name']; 

        }
        else { $Subcontractor_name="";}



 //   var_dump($site_name);

$sql = $wpdb->prepare("select i.siteID
     , i.siteNAME
     , i.equipmentTYPE
     , c.latitude
     , c.longitude
     , c.height 
     , o.ownerNAME
     , o.ownerCONTACT
     , x.companyNAME
     , y.subcontractorCOMPANY
     , y.subcontractorNAME
     , y.subcontractorCONTACT
  from site_info i
  LEFT  
  JOIN owner_info o
    on i.ownerID = o.ownerID
  LEFT  
  JOIN company_info x
    on i.companyID = x.companyID
  LEFT 
  JOIN subcontractor_info y
    on i.subcontractorID = y.subcontractorID
    LEFT JOIN site_coordinates2 c
    on i.siteID=c.siteID 
    where 
    i.siteNAME = %s
    AND 
    o.ownerNAME = %s
    AND 
    x.companyNAME = %s
   ",$site_name,$owner_name,$company_name);

 $query_submit =$wpdb->get_results($sql, OBJECT);

    echo "<br>";
    echo "<br>";
//echo $sql;

//    var_dump($_POST['site_name']);

// table that will dsiplay the results based on the user's selection //
echo "<table class='t1' width='30%'> ";
echo     "<tr>";
echo           "<th>Site Name</th>";
echo           "<th>Owner Name</th>";
echo           "<th>Company Name</th>";
echo           "<th>Subcontractor Name</th>";
echo           "<th>Site ID</th>";
echo           "<th>Equipment Type</th>";
echo           "<th> Lattitude</th>";
echo           "<th>Longitude </th>";
echo           "<th> Height</th>";
echo           "<th> Owner Contact</th>";
echo           "<th> Sub Contact</th>";
echo           "<th> Sub company Name</th>";
echo   "</tr>";  


foreach ($query_submit as $obj) {

echo   "<tr>";       
echo         "<td>".$obj->siteNAME."</td>";
echo         "<td>".$obj->ownerNAME."</td>";
echo         "<td>".$obj->companyNAME."</td>";
echo         "<td>".$obj->subcontractorNAME."</td>";
echo         "<td>".$obj->siteID."</td>";
echo         "<td>".$obj->equipmentTYPE."</td>";
echo         "<td>".$obj->latitude."</td>";
echo         "<td>".$obj->longitude."</td>";
echo         "<td>".$obj->height."</td>";
echo         "<td>".$obj->ownerCONTACT."</td>";
echo         "<td>".$obj->subcontractorCONTACT."</td>";
echo         "<td>".$obj->subcontractorCOMPANY."</td>";
echo  "</tr>";            
//$arrayOBJ = (array)$obj;
echo json_encode($obj);
//var_dump($arrayOBJ);
}    

?>

<script type="text/javascript">

// make Dropdownlist depend on each other
$(document).ready(function(){
  $('#site_name').on('change'function(){
    var SITENAME = $(this).val();

   if(SITENAME){
    $.ajax({
     url: 'search_info_location.php',
     type:'POST',
     data:'site_name='+SITENAME,
     dataType: 'json',
     success:function(html){

        $('#owner_name').html(html);
        $('#Company_name').html('<option value="">Select Owner Name</option>');
     }

    });
   }
   else{
      $('#owner_name').html('<option value="">Select Site Name first</option>');
      $('#Company_name').html('<option value="">Select Owner Name first</option>'); 
   }
  });

  $('#owner_name').on('change',function(){
     var OWNERNAME = $(this).val();
     if(OWNERNAME){
        $.ajax({
           type:'POST',
           url:'search_info_location.php',
           data:'owner_name='+OWNERNAME,
           success:function(html){
             $('#Company_name').html(html);
           }

        });
     }else{
        $('#Company_name').html('<option value="">Select Owner Name first</option>');
     }

  });

});




     var map,currentPopup;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: new google.maps.LatLng(33.888630, 35.495480),
          mapTypeId: 'roadmap'
        });

        var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
        var icons = {
          parking: {
            icon: iconBase + 'parking_lot_maps.png'
          },
          library: {
            icon: iconBase + 'library_maps.png'
          },
          info: {
            icon: iconBase + 'info-i_maps.png'
          }
        };




        function addMarker(feature) {
          var marker = new google.maps.Marker({
            position: feature.position,

            //icon: icons[feature.type].icon,
            map: map
          });

          var popup = new google.maps.InfoWindow({
                   content: '<b>Site ID :</b> ' + feature.info +'<br></br>' 
                   + '<b> Site Name :</b>' + feature.site_name +'<br></br>'  
                   + '<b>Coordinates :</b> '+ feature.position +'<br></br>' 
                   + '<b>height :</b> ' + feature.height,
                   maxWidth: 300
                });

          google.maps.event.addListener(marker, "click", function() {
                    if (currentPopup != null) {
                        currentPopup.close();
                        currentPopup = null;
                    }
                    popup.open(map, marker);
                    currentPopup = popup;
                });
                google.maps.event.addListener(popup, "closeclick", function() {
                    map.panTo(center);
                    currentPopup = null;
                });
        }



        var features = [
        <?php
            $prependStr ="";
            foreach( $wpdb->get_results("select c.siteID, c.latitude, c.longitude, c.height 
                                         , i.siteNAME
                                         FROM site_coordinates2 c LEFT 
                                         JOIN site_info i
                                         on c.siteID = i.siteID 
                                         where i.siteNAME = '".$site_name."'", OBJECT) as $key => $row) {
               $latitude = $row->latitude;
               $longitude = $row->longitude;
               $siteid = $row->siteID;
               $height = $row->height;
               $siteName = $row->siteNAME;
           echo $prependStr;
       ?>
{
    position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
    info:'<?php echo $siteid;?>',
    height: '<?php echo $height;?>',
    site_name: '<?php echo $siteName;?>',

}
<?php
$prependStr =",";
}
?>
        ];



        for (var i = 0, feature; feature = features[i]; i++) {

          addMarker(feature);
       }
}

         </script>
 <?php        



echo "</table>";

 }

?>    

<!--  the below part  of code work as it should   --!>
    <!--create  dropdown list site names-->

    <form method ="post" action ="" name="submit_form">
        <table border="0" width="30%">
            <tr>
               <td>Site Name</td>
               <td>Owner Name</td>
               <td>Company Name</td>
               <td>Subcontractor Name</td>
             </tr>
             <tr>
               <td><select id="site_name"  name = "site_name">

                 <?php


                     $query_site_name =$wpdb->get_results("select DISTINCT siteNAME  from site_info");
                      foreach($query_site_name as $site_name)
                      {
            //           $site_name = (array)$site_name;
                       echo "<option value = '".$site_name ->siteNAME."'>".  $site_name->siteNAME."</option>";
                      } 
                 ?>

                <!--create  dropdown list owner names-->
                </select></td>

                <td><select id="owner_name"  name ="owner_name">
                <?php
                 global $owner_name;
                      $query_owner_name =$wpdb->get_results ("select DISTINCT ownerNAME  from owner_info");
                      foreach($query_owner_name as $owner_name)
                      {
          //               $owner_name = (array)$owner_name;
                         echo "<option value = '".$owner_name->ownerNAME."'>".  $owner_name->ownerNAME."</option>";
                      } 
                  ?>
                </select></td>

                <!--create  dropdown list Company names-->
                </select></td>

                <td><select id="Company_name"  name ="Company_name">
                <?php 
                global $Company_name;
                     $query_Company_name =$wpdb->get_results ("select DISTINCT companyNAME  from company_info");
                     foreach($query_Company_name as $Company_name)
                     {
        //               $Company_name = (array)$Company_name;
                       echo "<option value = '".$Company_name->companyNAME."'>".  $Company_name->companyNAME."</option>";
                     }  
                 ?>
                </select></td>

                <!--create  dropdown list Subcontractor names-->
                </select></td>

                <td><select id="Subcontractor_name"  name ="Subcontractor_name">
                <?php 
                global $Subcontractor_name;
                    $query_Subcontractor_name =$wpdb->get_results ("select DISTINCT subcontractorNAME  from subcontractor_info");
                     foreach($query_Subcontractor_name as $Subcontractor_name)
                     {
      //                 $Subcontractor_name = (array)$Subcontractor_name;
                       echo "<option value = '".$Subcontractor_name->subcontractorNAME."}'>".  $Subcontractor_name->subcontractorNAME."</option>";
                      } 
                   ?>
                </select></td>
            <tr>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td>
            <input type ="submit" name="query_submit" value ="Search" />

        </td>
       </tr>

        </table>
    </form>

  </body>
</html>

<?php
get_footer();
?>    
1

1 Answer 1

2

Try the following pure JS implementation -

var stateObject = {
  "Three Wheelers": {
    "Bajaj": ["Bajaj RE CNG", "Bajaj Diesel"],
    "Atul": ["Piaggo", "Shakti"]
  },
  "Two Wheelers": {
    "Hero": ["Splendor", "CBZ"],
    "Honda": ["Hornet", "CBR"],
  },
  "Car": {
    "Suzuki": ["Swift", "Ciaz", "Baleno", "Dzire", "Brezaa", "Ertiga", "Celerio", "Eco", "Omni", "Alto", "Scross", "Ignis", "WagonR"],
    "Hyundai": ["i20", "i10", "Creat", "Eon", "Xcent", "Santro", "Tucson", "Elatrna"],
    "Volkswagon": ["Jetta", "Polo", "Passata", "Polo", "Tiguan", "Ameo"],
    "Nissan": ["Terrano", "Duster", "Micra", "Sunny"],
    "Honda": ["City", "Verna", "CR-V", "Accord", "BR-V", "Brio", "Amaze", "Jazz"],
    "Ford": ["EcoSports", "Endaviour", "Figo", "Freestyle", "Aspire"],
  }

}
window.onload = function() {
  var stateSel = document.getElementById("stateSel"),
    countySel = document.getElementById("countySel"),
    citySel = document.getElementById("citySel");
  for (var state in stateObject) {
    stateSel.options[stateSel.options.length] = new Option(state, state);
  }
  stateSel.onchange = function() {
    countySel.length = 1; // remove all options bar first
    citySel.length = 1; // remove all options bar first
    if (this.selectedIndex < 1) {
      countySel.options[0].text = "Select Brand"
      citySel.options[0].text = "Select Modal"
      return; // done   
    }
    countySel.options[0].text = "Select Brand"
    for (var county in stateObject[this.value]) {
      countySel.options[countySel.options.length] = new Option(county, county);
    }
    if (countySel.options.length == 2) {
      countySel.selectedIndex = 1;
      countySel.onchange();
    }

  }
  stateSel.onchange(); // reset in case page is reloaded
  countySel.onchange = function() {
    citySel.length = 1; // remove all options bar first
    if (this.selectedIndex < 1) {
      citySel.options[0].text = "Please Modal"
      return; // done   
    }
    citySel.options[0].text = "Please Modal"

    var cities = stateObject[stateSel.value][this.value];
    for (var i = 0; i < cities.length; i++) {
      citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
    }
    if (citySel.options.length == 2) {
      citySel.selectedIndex = 1;
      citySel.onchange();
    }

  }
}
<select id="stateSel" size="1" name="vehicle_type" class="form-control input" required>
  <option value="" selected="selected">Select Vehicle</option>
</select>
<br>
<br>
<select id="countySel" size="1" name="brand" class="form-control input" required>
  <option value="" selected="selected">Select Brand</option>
</select>
<br>
<br>
<select id="citySel" size="1" name="modal" class="form-control input" required>
  <option value="">Select Modal</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.