Populate 2 dropdown select lists based on change event from 1st

I have a dropdown list that triggers a change event that populates a second select list via jquery and php. What I need to do is, when the first event is triggered, populate dropdown 2 with the callback data and then query the database with the value of dropdown 2 and place result in dropdown 3.

 Where I am stuck is that I do not know how to query db from this sort of event.

I have posted the code I am currently using and would be grateful for any help with this as I am not sure what direction to go. Many thanks.

jquery code

$(function() {
  $("#dstr_dept").change(function() {
    $(this).after('<div id="loader"><imgages src="img/loading.gif" alt="loading files" /></div>');
    $.get('loadboxDstrsubcat.php?dstrdept=' + $(this).val(), function(data) {
      $("#box_dstr").html(data);
      $('#loader').slideUp(200, function() {
        $(this).remove();
        $("#box_dstr").trigger("chosen:updated"); 
      });
    });
  });
});

Open in new window


php code

<?php
 session_start();
?>

<?php
    include('../Connections/domain.php');

    $dstrdept = $_GET['cltdstrdept'];
    $customer = $_SESSION['kt_idcode_usr'];

    mysql_select_db($database_domain, $domain);
    $query = "SELECT name FROM departments WHERE code = '".$dstrdept."' ORDER BY name ASC";
    $result = mysql_query($query) or die (mysql_error());

    if (mysql_num_rows($result) > 0) {

    echo "<script type=text/javascript>\n";
    echo "$(function() {\n";
    echo "$(\".noBdstrBoxes\").html('')\n";
    echo "$('#dstr_dept').attr('data-placeholder', \"Choose your dept...\").prop('disabled', false)\n";
    //echo "$(\"#box_dstr\").prop('disabled', false)\n";
    //echo "$('#Frtv').show()\n";
    echo "});\n";
    echo "</script>\n";

    // This returns the data of departments
    while($row = mysql_fetch_array($result)) {
    echo "<option value='$row[name]'>$row[name]</option>";
    }    

    } else {

    echo "<script type=text/javascript>\n";
    echo "$(function() {\n";
    echo "$('.noBdstrBoxes').html('ERROR: There are no boxes to destroy in that dept. Please select another.').css({\"color\":\"red\", \"margin\": \"-6px 0 10px 22px\", \"font-size\": \"12px\", \"font-family\": \"Verdana, Geneva, sans-serif\"})\n";
    echo "$('#box_dstr').attr('data-placeholder', \"No boxes to display...\").prop('disabled', true)\n";
    echo "});\n";
    echo "</script>\n";

    //echo "<option value='No boxes in that dept'>No boxes in that dept</option>";

    }
?>

Open in new window


html code

<div class="fieldset">
          <h1><span>Select a Customer</span></h1>
          <p>
            <select data-placeholder="Choose a customer..." class="chosen-select" style="width:250px;" name="dstr_customer" id="dstr_customer">
              <option value=""></option>
                <option value="DEMO">DEMO</option>
                <option value="DEMO2">DEMO2</option>
                <option value="DEMO3">DEMO2</option>
                <option value="DEMO4">DEMO2</option>
            </select>
            <span></span>
            <a href="javascript:void(0)" style="margin-left:10px;" class="tooltip" title="Please select a dept where the box to be destroyed is stored.">Help</a>
          </p>
        </div>

<div class="fieldset">
          <h1><span>Select a Department</span></h1>
          <p>
            <select data-placeholder="Choose a dept..." class="chosen-select" style="width:250px;" name="dstr_dept" id="dstr_dept">
              <option value=""></option>

            </select>
            <span></span>
            <a href="javascript:void(0)" style="margin-left:10px;" class="tooltip" title="Please select a dept where the box to be destroyed is stored.">Help</a>
          </p>
        </div>

<div class="fieldset">
          <h1><span>Select an Address</span></h1>
          <p>
            <select data-placeholder="Choose an address..." class="chosen-select" style="width:250px;" name="dstr_address" id="dstr_address">
              <option value=""></option>

            </select>
            <span></span>
          </p>
        </div>

<div class="fieldset">
          <h1><span>Select Your Box(es)</span></h1>
          <p>
            <select data-placeholder="Choose your box(es)..." class="chosen-select" name="box_dstr[]" id="box_dstr" multiple required="required">
              <option value=""></option>
            </select>
            <span></span>
            <a style="margin-left: 12px;" href="javascript:void(0)" class="tooltip" title="Please select your boxes from the list. You can select a max of 20 boxes per submission.<br />.<br />You can select multiple boxes by holding the left ctrl on your keyboard and making your selection">Help</a>
          </p>
          <div class="noBdstrBoxes"></div>
        </div>

Open in new window

peter-cooperAsked:
Who is Participating?
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
Yes you can make 2 calls, but the alternative is that you get json object in your single call like
$.get('loadboxDstrsubcat.php?dstrdept=' + $(this).val(), function(data) {

      var json = JSON.parse(data);
      $("#box_dstr").html(data.boxes);
      $("#dstr_address").html(data.address);

});

Open in new window


In your php, your output will be

$response['boxes'] = HTML_FOR_BOXES_SELECT;
$response['address'] = HTML_FOR_ADDRESS_SELECT;

echo json_encode(response);

Open in new window

0
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
Hi Peter,

Instead of using your own you can use http://www.appelsiini.net/projects/chained

Thanks
0
 
Ahmed MerghaniSoftware EngineerCommented:
You need to do that with AJAX. When the drop down list trigger a change, an AJAX call need to be happened to send the selected item from the list to server. At server, do your query based on selected item and send result back to client. Result can be well formatted html code for drop down 2. Or can be JSON format contains the OPTION and its VALUE. At the client using jQuery, you can place the result.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
peter-cooperAuthor Commented:
@Ahmed do you have working example please. Thanks
0
 
peter-cooperAuthor Commented:
@Shahzad Thanks for link but I would rather try to find a solution based on my existing code rather than change it all. Thanks
0
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
For your code, what you can do is, have individual callback function for every dropdown which will be triggered on change.

These callback will hit different urls for fetching specific results based on the parameters passed. Here is a sample explanation.


var _callbacks = {
 // callback for getting dept on change of customer dropdown
 dept: function(){
  // Add loader, get depts for customer
  // when data received, add the data in dept select box and trigger change for that and remove loader
},
 address: function(){
  // Add loader, get address for dept
  // when data received, add the data in addresses select box and trigger change for that and remove loader
},
 boxes: function(){
 // Add loader, get boxes for address
  // when data received, add the data in boxes select box and remove loader
}
}

// attach events on select boxes when page loads
$(document).ready(function(){
   $('select#dstr_customer').on('change', _callbacks.dept);
   $('select#dstr_dept').on('change', _callbacks.address);
   $('select#dstr_address').on('change', _callbacks.boxes);
})

Open in new window

0
 
peter-cooperAuthor Commented:
@Shahzad

Thanks for that. However, I am not sure how to incorporate your code into mine. Could you please help with this. Also, I need to populate both the address select and the box select from the dept change event.  You have them as individual change events. Thanks
0
 
peter-cooperAuthor Commented:
I have managed to follow the logic, but get 'ReferenceError: _callbacks is not defined' when the page loads. Here is a sample of code which i put together. Where have I gone wrong? Thanks

$(function() {
var _callbacks = {
 // callback for getting dept on change of customer dropdown
 dept: function(){
  // Add loader, get depts for customer
  // when data received, add the data in dept select box and trigger change for that and remove loader
  
  $(this).after('<div id="loader"><imgages src="img/loading.gif" alt="loading files" /></div>');
    $.get('loadboxClientDstrsubcat.php?cltdstrdept=' + $(this).val(), function(data) {
      $("#dstr_dept").html(data);
      $('#loader').slideUp(200, function() {
        $(this).remove();
        $("#dstr_dept").trigger("chosen:updated");
      });
    });
},
 address: function(){
  // Add loader, get address for dept
  // when data received, add the data in addresses select box and trigger change for that and remove loader
},
 boxes: function(){
 // Add loader, get boxes for address
  // when data received, add the data in boxes select box and remove loader
}
}
});

// attach events on select boxes when page loads
$(function(){
   $('select#dstr_customer').on('change', _callbacks.dept);
   $('select#dstr_dept').on('change', _callbacks.address);
   $('select#dstr_address').on('change', _callbacks.boxes);
});

Open in new window

0
 
peter-cooperAuthor Commented:
@Shahzad

For some weird reason, I put the callback function in doc ready. Removed and error gone.
0
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
Did the final version of your code work for you?
Did it resolve your original issue?
0
 
peter-cooperAuthor Commented:
@Shahzad

Also, I need to populate both the address select and the box select from the dept change event.  You have them as individual change events. Thanks

This is what I need to happen. Thanks
0
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
You will need to add your logic in the callback functions.
0
 
peter-cooperAuthor Commented:
Seems to me that I have to make 2 db calls from one change event. 1 for dept and 1 for address. Is that possible. Thanks
0
 
peter-cooperAuthor Commented:
Thank you very much
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.