Question

I need some serious help or advise on something that I've spend countless hours on researching and coming up empty.

I have a project where I need to pull data from an MDB database using PHP. I have succeeded in connecting to the database, I can query the database and display the results in a table and I can even search the database using a text input.

My client wants an advanced search functionality with multiple dropdowns. These dropdowns are getting the values from the database. All this is still fine. I can populate the dropdowns from the database.

The database is a vehicles database (Id, Stock Number, Make, Model, Year, Price, Features etc). Unfortunately all the vehicle data is in one table. So for example, there are four ASTON MARTIN cars in the database, each with it's own ID and model.

I know that it would be best to have at least two separate tables: make and model. But the database is generated by a third party application which saves a copy of the database to the server and that's the one I connect to.

The question is: using PHP and AJAX, would it be possible to have cascading dropdowns when drawing data from the same table? So for example, if I chose ASTON MARTIN from the Make selection, the second dropdown would only show the models related to ASTON MARTIN?

Please see the below attempt at trying this... This script successfully loads the Make column from the database to the first dropdown, and the Modal column from the database to the second dropdown, but they are not linked. As it currently is, the first option is ASTON MARTIN and it's corresponding model is CORSA (That's not at all correct).

     <script type="text/javascript">

          function loadXMLDoc() {
          var xmlhttp;
           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) {
         document.frm.modelSelection.innerHTML=xmlhttp.responseText;
           }
       }

        var makevalue=document.frm.makeSelection.value;

        xmlhttp.open("GET","?ajaxmake="+makevalue,true);
        xmlhttp.send();
            }

            </script>

            <?php 

            $dbName = "C:/xampp/htdocs/new/db/savvyautoweb.mdb";

            // Throws an error if the database cannot be found
            if (!file_exists($dbName)) {
            die("Could not find database file.");
            }

            // Connects to the database
            // Assumes there is no username or password
            $conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');

            ?>

            <form action="" method="post" name="frm">
        <select name="makeSelection" onchange="loadXMLDoc()">

            <?php
         $resultMake = odbc_exec($conn, "SELECT Make FROM Vehicle ORDER BY Make") or die (odbc_errormsg());
         while ($rowMake = odbc_fetch_array($resultMake)) {
     echo "<option value='$rowMake[Make]'>$rowMake[Make]</option>";
         }
              ?>
           </select>
           <select name="modelSelection">

            <?php
        if (isset($_REQUEST['ajaxmake'])) {
        $resultModel = odbc_exec($conn, "SELECT Model FROM Vehicle") or die (odbc_errormsg());

         while ($rowModel = odbc_fetch_array($resultModel)) {
           echo "<option value='$rowModel[Model]'>$rowModel[Model]</option>";
         }

         die();
             }
                 ?>
             </select>
             <input type="submit" name="submit" value="Go">
                 </form>

EDIT brought on to code above based on your solution. Thank you for this.

The function seems to work, but it populates the second dropdown with the make column and not the model column. Any idea why?

Thank you, Deon Jonker

Was it helpful?

Solution

For your select, you could add an onchange attribute like this

<select name="makeselection" onchange="filtermodelselection()">

You add a function filtermodelselection(), which reads out the selected option from your makeselection like (give a name to your form, or an id to your select, I'll use "frm" now as formname)

var makeid=document.frm.makeselection.value;

You send your ajax request to the page. then with the makeid you can make an ajax request to the server like this : http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get_unique

function loadXMLDoc()
{
var xmlhttp;
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)
    {
    document.frm.modelSelection.innerHTML=xmlhttp.responseText;
    }
  }
var makevalue=document.frm.makeSelection.value;
xmlhttp.open("GET","?ajaxmake="+makevalue,true);
xmlhttp.send();
}

On the server side you get a $_REQUEST['ajaxmake'] variable.

if (isset($_REQUEST['ajaxmake'])) {
   //do the magic the query, and then echo like what you did here:
while ($rowModel = odbc_fetch_array($resultModel)) {
    echo "<option value='$rowModel[Model]'>$rowModel[Model]</option>";
}
//then die, to not echo anything else accidentally
die();
}

example output:

<option value='AUDI'>AUDI</option>
<option value='BMW'>BMW</option>

on the recieving side, with ajax you give the recieved value from the server to the modelSelection's innerHTML.like:

document.frm.modelselection.innerHTML=xmlhttp.responseText;

If something is not clear, please feel free to ask.

EDIT: put this part:

<?php
        if (isset($_REQUEST['ajaxmake'])) {
        $resultModel = odbc_exec($conn, "SELECT Model FROM Vehicle") or die (odbc_errormsg());

         while ($rowModel = odbc_fetch_array($resultModel)) {
           echo "<option value='$rowModel[Model]'>$rowModel[Model]</option>";
         }

         die();
             }
   ?>

to the beginning of the file. (after any includes, database connector codes of course)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top