Solved

PHP and AJAX for dependent dropdown box

Posted on 2014-02-14
8
782 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 43

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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
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
 
LVL 43

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 43

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

738 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