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
    8

    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,716
    what kind of error it shows? did you try to alert(xhr.responseText); ?
    signature under construction

  3. #3
    Join Date
    May 2013
    Posts
    8
    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,716
    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)">
    signature under construction

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

  6. #6
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,716
    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
    signature under construction

  7. #7
    Join Date
    May 2013
    Posts
    8
    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,716
    try to change this line var catid = this.value; in your updateSubCats() function into var catid = this.options[this.selectedIndex].value;
    signature under construction

  9. #9
    Join Date
    May 2013
    Posts
    8
    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,716
    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)?
    signature under construction

  11. #11
    Join Date
    May 2013
    Posts
    8
    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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.48509 seconds
  • Memory Usage 2,965KB
  • Queries Executed 15 (?)
More Information
Template Usage (33):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (9)bbcode_code
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (11)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (11)postbit
  • (11)postbit_onlinestatus
  • (11)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (73):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates