www.webdeveloper.com
Results 1 to 11 of 11

Thread: Retrieve HTML drop down list value with AJAX

  1. #1
    Join Date
    May 2013
    Posts
    6

    Retrieve HTML drop down list value with AJAX

    I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX? Here is my code:
    Code:
    <script type = "text/javascript">
    function getData(str){
        var xhr = false;
        if (window.XMLHttpRequest) {
                // IE7+, Firefox, Chrome, Opera, Safari
                xhr = new XMLHttpRequest();
            } 
            else {
                // IE5/IE6
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xhr) {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.getElementById("div1").innerHTML = xhr.responseText;
                    }
                }
                xhr.open("GET", "/display-product.php?q="+str, true);
                xhr.send(null);
            }
    }
    </script>
    This is my HTML drop down list:
    Code:
    <div>
              <?php
               echo '<select title="Select one" name="selectcat" onChange="getData(this.value)">';
               while($row1 = $result->fetch_assoc()){            
               echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
                }
               echo '</select>';
                ?>
                </div>
    And this is the div where i want the selected contents to be printed:
    Code:
    <div class="product_directory" id="div1"></div>
    The code doesn't work for some reason. Thanks in advance for any help

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,635
    what kind of error it shows? did you try to alert(xhr.responseText); ?
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  3. #3
    Join Date
    May 2013
    Posts
    6
    yes alert(xhr.responseText) doesn't show any alertbox.
    I can acess the "str" variable passed to the function in my PHP using this assignment right?: "$string = $_GET['q']"
    Because I'm now getting the error: Undefined index q

  4. #4
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,635
    btw, as i know this line (in the php-part of your code) onChange="getData(this.value)"> usually looks like onChange="getData(this.options[this.selectedIndex].value)">
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  5. #5
    Join Date
    May 2013
    Posts
    6
    okay. I implemented that and still no output

  6. #6
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,635
    all i can suspect is:

    1. wrong path to the php-file at the line xhr.open("GET", "/display-product.php?q="+str, true)
    2. wrong php code

    i created a demo

    index.php

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>ajax</title>
    <style type="text/css">
    body{color:#000;background-color:#fff;font-family:'Bookman Old Style',Georgia,Verdana;font-size:14px;text-align:center;font-weight:bold;}
    </style>
    <script type = "text/javascript">
    function getData(str){
        var xhr = false;
        if (window.XMLHttpRequest) {
                // IE7+, Firefox, Chrome, Opera, Safari
                xhr = new XMLHttpRequest();
            } 
            else {
                // IE5/IE6
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xhr) {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
    				//alert(xhr.responseText);
                        document.getElementById("div1").innerHTML = xhr.responseText;
                    }
                }
                xhr.open("GET", "display-product.php?q="+str, true);
                xhr.send(null);
            }
    }
    </script>
    </head>
    <body>
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    <div>
              <?php
               echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value);this.blur()"><option value="0">choose product</option>';
               for($x=1; $x<5; $x++){            
               echo '<option value="' . $x . '">option ' . $x . '</option>';
                }
               echo '</select>';
                ?>
    
    </div>
    <br /><br /><br />
    <div class="product_directory" id="div1">div class="product_directory" id="div1"</div>
    </body>
    </html>
    display-product.php

    Code:
    <?php
    if(!isset($_GET['q']) || empty($_GET['q'])){return;}
    else{echo '<h2>q = '.$_GET['q'].'</h2>';}
    ?>
    live demo as you can see everything works ok
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  7. #7
    Join Date
    May 2013
    Posts
    6
    I was able to figure out the source of the problem but not the solution. I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
    Code:
    <script type="text/javascript">
    <?php
    echo "var categories = $jsonCats; \n";
    echo "var subcats = $jsonSubCats; \n";
    ?>
    function loadCategories(){
            var select = document.getElementById("categoriesSelect");
            select.onchange = updateSubCats;
            for(var i = 0; i < categories.length; i++){
              select.options[i] = new Option(categories[i].val,categories[i].id);          
            }
    }
    function updateSubCats(){
            var catSelect = this;
            var catid = this.value;
            var subcatSelect = document.getElementById("subcatsSelect");
            subcatSelect.options.length = 0; //delete all options if any present
            for(var i = 0; i < subcats[catid].length; i++){
              subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
            }
          }
    </script>
    The code works fine if i manually put <options> in the select list as in the demo. But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
    <body onload = "loadCategories()">.
    The other select box is very similar to this one.
    Everything else is same as in the demo. I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats(). Do you have an idea of what is wrong?

  8. #8
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,635
    try to change this line var catid = this.value; in your updateSubCats() function into var catid = this.options[this.selectedIndex].value;
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  9. #9
    Join Date
    May 2013
    Posts
    6
    Thanks but still doesn't work if i change it.
    PS: "this.value" works almost the same as "this.options[this.selectedIndex].value;"

  10. #10
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,635
    still doesn't work is not an error. what is the error you are getting? what is printed here

    Code:
    <?php
    echo "var categories = $jsonCats; \n";
    echo "var subcats = $jsonSubCats; \n";
    ?>
    ?

    what does error console/firebug/something else say about the error(s)?
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  11. #11
    Join Date
    May 2013
    Posts
    6
    Code:
    <?php
    echo "var categories = $jsonCats; \n";
    echo "var subcats = $jsonSubCats; \n";
    ?>
    Nothing is printed, it just creates an array "categories" and "sub-cats". Similar to this
    Code:
    var categories = ["one", "two", "three"];
    var subcats = [
        ["one", "two", "three"],
        ["uno", "dos", "tres"],
        ["apple", "orange", "banana"]
    ];
    I'm not getting any error messages. The selected content just doesn't display. I don't know why.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles