1

Below I have a piece of code where it is suppose to display 2 drop down menus, one for building and other for rooms. What happens is when the user selects a building from the building drop down menu, using the ajax/jquery it will navigate to the room.php page and lists the rooms that belongs to the building selected and displays the list of rooms in the rooms drop down menu. This works fine:

<script type="text/javascript">

    function getRooms() { 
    var building = jQuery("#buildingsDrop").val(); 
    jQuery('#roomsDrop').empty(); 
    jQuery('#roomsDrop').html('<option value="">Please Select</option>'); 
    jQuery.ajax({ 
          type: "post", 
          url:  "room.php", 
          data: { building:building }, 
          success: function(response){ 
              jQuery('#roomsDrop').append(response); 
          } 
        }); 


 }

</script>

...

<?php

 $sql = "SELECT DISTINCT Building FROM Room"; 

 $sqlstmt=$mysqli->prepare($sql);

 $sqlstmt->execute(); 

 $sqlstmt->bind_result($dbBuilding);

 $buildings = array(); // easier if you don't use generic names for data 

 $buildingHTML = "";  
 $buildingHTML .= '<select name="buildings" id="buildingsDrop" onchange="getRooms();">'.PHP_EOL; 
 $buildingHTML .= '<option value="">Please Select</option>'.PHP_EOL;  

 while($sqlstmt->fetch()) 
 { 
     $building = $dbBuilding; 
     $buildingHTML .= "<option value='".$building."'>" . $building . "</option>".PHP_EOL;  
  } 

  $buildingHTML .= '</select>'; 

  $roomHTML = "";  
  $roomHTML .= '<select name="rooms" id="roomsDrop">'.PHP_EOL; 
  $roomHTML .= '<option value="">Please Select</option>'.PHP_EOL;  
  $roomHTML .= '</select>'; 

?>

room.php:

$building = isset($_POST['building']) ? $_POST['building'] : '';

$sql = "SELECT Room FROM Room WHERE Building = ?";
$sqlstmt=$mysqli->prepare($sql);
$sqlstmt->bind_param("s",$building);
$sqlstmt->execute();
$sqlstmt->bind_result($dbRoom);

$roomHTML  = "";

while($sqlstmt->fetch()) {
    $roomHTML .= "<option value='".$dbRoom."'>" . $dbRoom . "</option>".PHP_EOL;
}
echo $roomHTML;

The problem I am having though is the when a user selects an assessment, it is suppose to display the assessment's building and room options in the relevant drop down menus. But it is not selecting those options, they remain on the "Please Select" option. Why is this and how can I get the options shown?

Below is the view source code:

    //Assessment drop down menu:

    <p><strong>Assessments:</strong> <select name="session" id="sessionsDrop">
    <option value="">Please Select</option>
    <option value='71' style='color: green'>AKXMB - 30-11-2012 - 10:00</option>
    </select> </p>   
    </form>

    //Building drop down menu:

    <select name="buildings" id="buildingsDrop" onchange="getRooms();">
    <option value="">Please Select</option>
    <option value='Canalside East'>Canalside East</option>
    <option value='Canalside West'>Canalside West</option>
    </select>


    //Room drop down menu (list of rooms displayed in room.php):

    <select name="rooms" id="roomsDrop">
    <option value="">Please Select</option>
    </select>

    //Retrieve assessment information 
    //(Below is where problem lies where it is not selecting building and room options in drop down menu)
    <script type="text/javascript">

$(document).ready( function(){

                var sessioninfo = [{"SessionId":71,"Building":"Canalside East","Room":"CE01\/04"},{"SessionId":84,"Building":"Canalside East","Room":"CE01\/04"}];

                $('#sessionsDrop').change( function(){

                    var sessionId = $(this).val();

                    if (sessionId !== '') {
                for (var i = 0, l = sessioninfo.length; i < l; i++)
                {
                        if (sessioninfo[i].SessionId == sessionId) { 

                var currentbuilding = $('#currentBuilding').val(sessioninfo[i].Building);
                var editbuilding = $('#BuildingsDrop').val(sessioninfo[i].Building);
                var currentroom = $('#currentRoom').val(sessioninfo[i].Room);
                var editroom = $('#RoomsDrop').val(sessioninfo[i].Room);
                var currentid = $('#currentId').val(sessioninfo[i].SessionId);
                var editid = $('#newId').val(sessioninfo[i].SessionId);

                        break;
                }
               }
             }

                });
            });
</script>

UPDATE:

Application

  • In the application select a "Module" from drop down menu and submit.

  • Below it should show some features. In the Assessment drop down menu select any assessment.

  • You can see underneath that for "Current Assessment Details" it displays the building and room in the readonly text inputs to indicate what is the assessment's current building and room.

  • I want the same building and room to be selected in the drop down menus in the "New Assessment's Room" section. You can see the building is selected in the Building drop down menu but the Room is not selected in the Room drop down menu.

user1914374
  • 1,220
  • 2
  • 11
  • 21

1 Answers1

1

Unless this was a copy/paste error, you are missing your <script></script> tags around your assessment function/script -

<script type="text/javascript">
$(document).ready( function(){

...
    });
</script>

Edit

Your issue is that your id's are wrong case -

        ...
        var editbuilding = $('#BuildingsDrop').val(sessioninfo[i].Building);
        ...
        var editroom = $('#RoomsDrop').val(sessioninfo[i].Room);

Change to -

        ...
        var editbuilding = $('#buildingsDrop').val(sessioninfo[i].Building);
        ...
        var editroom = $('#roomsDrop').val(sessioninfo[i].Room);

see also - In the DOM are node ids case sensititve?

Edit - 2
Just add getRooms() just before var editroom to populate #roomsDrop so then you can set the selected.

var currentbuilding = $('#currentBuilding').val(sessioninfo[i].Building);
var editbuilding = $('#buildingsDrop').val(sessioninfo[i].Building);
var currentroom = $('#currentRoom').val(sessioninfo[i].Room);
getRooms();
var editroom = $('#roomsDrop').val(sessioninfo[i].Room);
var currentid = $('#currentId').val(sessioninfo[i].SessionId);
var editid = $('#newId').val(sessioninfo[i].SessionId);

Edit - 3

By default, $.ajax runs asynchronously in the browser, so the issue is that before your are getting to success: function(response){} in function getRooms() it has already moved on to var editroom = $('#roomsDrop').val(sessioninfo[i].Room);, and since jQuery('#roomsDrop').append(response); has not appended the option values to roomsDrop there is nothing to select. This can be fixed in 2 ways -

(1) quick fix using async: false

<script type="text/javascript">
    function getRooms() { 
    var building = jQuery("#buildingsDrop").val(); 
    jQuery('#roomsDrop').empty(); 
    jQuery('#roomsDrop').html('<option value="">Please Select</option>'); 
    jQuery.ajax({ 
          type: "post", 
          url:  "room.php", 
          data: { building:building },
          async: false, 
          success: function(response){ 
              jQuery('#roomsDrop').append(response); 
          } 
        }); 
 }
</script>

This makes the $.ajax call synchronously, so it will not proceed to var editroom = $('#roomsDrop').val(sessioninfo[i].Room); until after the success: function(response){} is done. note be aware that async: false freezes the browser while it waits for the response, so it may hold up any other actions.

(2) using a callback function -

<script type="text/javascript">
    function getRooms(callback) { 
    var building = jQuery("#buildingsDrop").val(); 
    jQuery('#roomsDrop').empty(); 
    jQuery('#roomsDrop').html('<option value="">Please Select</option>'); 
    jQuery.ajax({ 
          type: "post", 
          url:  "room.php", 
          data: { building:building },
          async: false, 
          success: function(response){ 
              jQuery('#roomsDrop').append(response);
              callback();
          } 
        }); 
 }
</script>    

AND

getRooms(function(){
var editroom = $('#roomsDrop').val(sessioninfo[i].Room);});

This callback function will execute the var editroom = $('#roomsDrop').val(sessioninfo[i].Room); after getRooms() has finished, but will continue the rest of the script without holding up the browser

Community
  • 1
  • 1
Sean
  • 12,443
  • 3
  • 29
  • 47
  • Sorry sean, that is a copy and paste error on SO, I have the tags in my application – user1914374 Jan 01 '13 at 18:01
  • I have updated my answer. Apparently you had your `id`'s for `buildingsDrop` & `roomsDrop` with wrong case (`BuildingsDrop` / `RoomsDrop`) – Sean Jan 01 '13 at 19:22
  • Im a fool for missing that. Ok so what is happening is the building is being selected but the room is still on please select but no room options are displayed in the drop down menu. Do I need to include `getRooms()` function in the juqery code somewhere? – user1914374 Jan 01 '13 at 19:34
  • Since `#roomsDrop` is empty, just call `getRooms()` before you want to set the selected value (but after you call `var editbuilding = $('#buildingsDrop').val(sessioninfo[i].Building);`). I have added it to my answer. – Sean Jan 01 '13 at 19:45
  • What happens is if I select an assessment, it displays a list of buildings in the buildings drop down and it selects the current assessment building in the drop down, this is fine. For the rooms drop down menu it is displaying the list of rooms which belongs with the building selected but it does not display the selected room option from the chosen assessment, it still displays `Please Select` option in rooms drop down menu. I have upvoted your answer. I will provide an update in my question giving you a link to the application. – user1914374 Jan 01 '13 at 20:09
  • Your link to -http://helios.hud.ac.uk/u0867587/Mobile_app/editroomadmin.php - is erroring out - `Parse error: syntax error, unexpected $end in /web/stud/u0867587/Mobile_app/editroomadmin.php on line 489` – Sean Jan 01 '13 at 20:17
  • Oops sorry, accidentally included an extra }, the application should be running now – user1914374 Jan 01 '13 at 20:38
  • Any luck with any ideas Sean? I still can't figure it out but still trying – user1914374 Jan 01 '13 at 23:50
  • I have done a little reading up on `$.ajax`. I edited my answer with two fixes - 1 using `async: false` & 1 using a callback function. see **Edit - 3** – Sean Jan 01 '13 at 23:51
  • Brilliant that works fine, can you send me the link on the ajax so that I can read it up to learn more about ajax please. Thanks – user1914374 Jan 02 '13 at 00:09