Solved

PHP and AJAX for dependent dropdown box

Posted on 2014-02-14
8
767 Views
Last Modified: 2014-02-14
I have a PHP page on our Intranet with two select boxes.  The source data is a single table in an Oracle DB.
Sample data is shown below:

CAT1                                    CAT2
Electrical Design                        Noise Susceptibility
Electrical Design                        Part Stress & Worst Case Design
Electrical Design                        Performance
Electrical Design                        Other
Literature and Communication      Did Not Meet Customer Expectation
Literature and Communication      Literature Incorrect
Literature and Communication      System Specificed Incorrectly
Literature and Communication      Web Problem
Literature and Communication      Other
Manufacturing                              Assembly Error
Manufacturing                              Operational Error
Manufacturing                              Solder Quality
Manufacturing                              Wrong/Missing Part
Manufacturing                              Tester Interaction
Manufacturing                              Other
Mechanical Design                        Interference
Mechanical Design                        Part Stress & Worst Case Design
Mechanical Design                        Thermal
Mechanical Design                        User Interface
Mechanical Design                        Aesthetics
Mechanical Design                        Other
Software Design                        Device Embedded Bug
Software Design                        Processor Embedded Bug
Software Design                        GUI Bug
Software Design                        Company_Name Product Compatibility
Software Design                        Tester Script Issue
Software Design                        Other
Standards                                    Does Not Meet Standards Requirements
Standards                                    Standards Markings
Standards                                    Other
Supplier                                    Manufacturing Defect
Supplier                                    Part out of Specification
Supplier                                    Poor Design
Supplier                                    Wrong Part
Supplier                                    Other
Documentation                        BOM
Documentation                        Label Database
Documentation                        Run Memo
NotAQualityProblem                  False Alarm
NotAQualityProblem                  Inventory Management
NotAQualityProblem                  Other
Engineering_StillNeedRoot            Engineering_StillNeedRoot
Manufacturing_StillNeedRoot            Manufacturing_StillNeedRoot
Supplier_StillNeedRoot                  Supplier_StillNeedRoot

I am loading The first select box with distinct CAT1 values.  When the user selects a value in CAT1, I want to run an AJAX script to populate CAT2 select box with distinct CAT2 values where CAT1 = what was selected.

My initial page is ReleaseHold.php.  Here is the code for that page for the dropdown and the onchange:

//****** get Lessons Learned categories ***************************************************************************************** 
    // display cat1 and leave cat2 for the AJAX call
    $query = "select DISTINCT CAT1 from yqiscom.rccategories order by CAT1 ASC";
    
    $LLcatRS = odbc_exec($link,$query);
    $LLcatRS1 = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Category: <select id='category' name='category' size=1><option value=NULL>Please select a category</option>";
    while (odbc_fetch_row($LLcatRS))
    {
        $LLcatRS1.= "<option value='". trim(odbc_result($LLcatRS,1)) . "'>". trim(odbc_result($LLcatRS,1)) . "</option>";        
    }
    $LLcatRS1.= "</select>";
    
    $LLcatRS2 = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sub Category:  <select id='subcategory' name='subcategory' size=1><option value=NULL>Please select a category, first</option></select>"; 

Open in new window


In that page I also have this jQuery code:

<script type="text/javascript" src="../../AJAX/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $(".category").change(function() {
            alert("In function!");
            var id=$(this).val(); 
            $.ajax( {
                type: "POST",
                url: "ajax_subcat.php",
                data: { id: id},
                cache: false,
                success: function(html) {
                    $(".subcategory").html(html);
                }
            });
        });
    });
</script>

Open in new window


ajax_subcat.php code is here:

<?  
    session_start();
    include '../determinelibrary.inc';
    include '../../Include_Files/ServerSide/connect_qisuser.inc';
    include '../../Include_Files/ServerSide/as400path.inc';
    include '../../Include_Files/ServerSide/getdate_time.inc';
    include "includes/sessionvarsRH.inc";

    if($_POST['id']) {
        $id = $_POST['id'];
        $query = "select DISTINCT CAT2 from yqiscom.rccategories WHERE CAT1 = '$id' order by CAT2 ASC";
        $LLsubcatRS = odbc_exec($link,$query);
        while (odbc_fetch_row($LLcatRS))
        {
            echo "<option value='". trim(odbc_result($LLsubcatRS,1)) . "'>". trim(odbc_result($LLsubcatRS,1)) . "</option>";        
        }
    }
?>

Open in new window


PROBLEM:
After the user selects an item from CAT1, I do not believe the onchange code is ever firing.  I even threw in an alert to see if I get to the function, but it never appears.
There is a separate body onload function.  Is that interfering with the jQuery document.onready?

I have never used jQuery or AJAX before.  I thought this would be a simple implementation, but I cannot get it to work.  Would like to get this working before end of day.

Thank you!
0
Comment
Question by:dimmergeek
  • 5
  • 3
8 Comments
 
LVL 7

Author Comment

by:dimmergeek
ID: 39859072
UPDATE:

The document.ready is firing.  (I added another alert box), but the $(".category").change(function() is not firing.
0
 
LVL 7

Author Comment

by:dimmergeek
ID: 39859084
UPDATE2:

The onchange is firing by putting in this $("#category") as the onchange specifier.

Second select box is still not being populated.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39859158
You're using class selectors but your SELECT have IDs, so instead of :

$(".category").change(function() {
and
$(".subcategory").html(html)

You need

$("#category").change(function() {
and
$("#subcategory").html(html)
0
 
LVL 7

Author Comment

by:dimmergeek
ID: 39859173
Thank you!  I got that working, and now the AJAX is firing.  However, after I select an item for CAT1, my CAT2 box gets cokmletely wiped out.  Even my default "Please select a category first" is getting wiped.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39859210
Right. It looks like you're using the wrong variable name in your subcat script:

You have this:

$LLsubcatRS = odbc_exec($link,$query);
while (odbc_fetch_row($LLcatRS))

which should probably be this:

$LLsubcatRS = odbc_exec($link,$query);
        while (odbc_fetch_row($LLsubcatRS))

While you're testing it makes sense to turn on error reporting in your scripts. Add this to the top of each PHP script

error_reporting(E_ALL);
ini_set('display_errors', 1);

Open in new window

It would have flagged the error :)
0
 
LVL 7

Author Comment

by:dimmergeek
ID: 39859280
Great!  That did it!  Any way I can force the CAT2 select box to adjust to size of longest returned value?  Some of the text is being cut off...
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39859315
Normally is would expand to fit the text, unless you have some CSS that sets the width.
0
 
LVL 7

Author Comment

by:dimmergeek
ID: 39859755
Thanks.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
This article discusses four methods for overlaying images in a container on a web page
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now