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? Thanks in advance.

Recommended Answers

All 25 Replies

Ok so, one way is to execute a function when the "onchange" event triggers. In this function, you send a request to your ASP, ASP.NET, PHP, etc.. page with the selection and the page will return the results back. then simply display the results or do whatever calculation with the data as you need to. For the drop down list, here is an example...

<select name="dropDown1" onchange="getData(this.value)">
    <option value="">-- Select --</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>

I have working example online that does what you are asking. I am going to provide you with hyperlink for the AJAX with PHP example, but I also have an ASP and ASP.NET example in the same series.

AJAX and PHP with SQL

Hope this helps..

Thanks. It does help. I can't get it to work though. I'm not very conversant with AJAX. I used similar code to that in your tutorial.

<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 my select list.

<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:

<div class="here">You selected:</div>
      <div class="product_directory" id="div1"></div>
      </div>

Where i'm i getting it wrong?

Have you verified your PHP page is working? You can check the page by accessing the page directly using the web browser connecting to the page on the web server. Also, the path to the filename doesnt appear correct to me. If this file is on the root of the web server you need to specify the relative, or absolute path. I'd try...

/display-product.php?q=

The page works. I also edited the url to read

/display-product.php?q=

but still doesn't display the selected value

Do you have this site online to take a look with debugging tools?

No i'm running it on a localhost (MAMP)

I can acess the str variable using this assignment right $string = $_GET['q']? I'm now getting the error: Undefined index q

Ok so it looks like the demo code that I provide you is correct. I created a demo online for you to look at. There are two files. Default.php and display-product.php. Here is the code:

default.php
<!DOCTYPE html>
<html>
<head>
  <title>Demo</title>
</head>
<body>
<script>
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("results").innerHTML = xhr.responseText;
                }
            }
            xhr.open("GET", "display-product.php?q="+str, true);
            xhr.send(null);
        }
}
</script>
<div>
        <?php
        echo '<select title="Select one" name="selectcat" onChange="getData(this.value)">';        
        echo '<option value="None">-- Select Option --</option>';
        echo '<option value="1">One</option>';
        echo '<option value="2">Two</option>';
        echo '</select>';
        ?>
</div>
<br/><br/>
<p>You selected: <span id="results"></span></p>

</body>
</html>

...

display-product.php
<?php

  echo $_GET["q"]

?>

..

This is a simplified example only to validate that the AJAX script is working which it is. If you run default.php and select an option, that value is send to display-product.php via AJAX. The display-product.php file simply takes the query string parameter of q and sends (echos) the value back to default.php where the script updates the span element with an id of "results".

Take a look at the demo, i will leave it up for a while.

http://itg.netai.net/demo/default.php

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:

<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()>.
Again this is how the first select box looks like:

<div>
        <?php
       echo '<select title="Select one" name="selectcat" id="categoriesSelect" onChange="getData(this.options[this.selectedIndex].text)">';        
       while($row1 = $result->fetch_assoc()){            

           echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
            }

           echo '</select>';

        ?>
</div>

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?

dhani09 are you open to using jQuery?

yes i am. But i don't know how to implement this with jQuery. I would appreciate some help anyway.

Ok, I need some more information about what you are wanting to accomplish. I don't want code, just a simple a, b, c, d... of the requirements

a. You populate your select options from a database table
b. you select a value from the drop down
c. ????

okay.
a. I want to populate the select options of two dropdown lists from a database
b. clicking an option in dropdown1(list of categories) populates options in dropdown2(list of subcategories). (e.g you choose a category in dropdown1 and its subcategories are listed in dropdown2)
c. whatever you select in either of the dropdowns is printed. e.g i select "one" from dropdown1 and "two" from dropdown2. it should print: You selected: one >> two.

Thanks.

First we'll get your "ajax page" working... which will display the subcategories

I've simulated a database with the following code. You will do real db queries.

<?php 
$databaseData = array(
    1 => array(1=>'Honda',2=>'Kawasaki',3=>'Suzuki',4=>'Yamaha'),
    2 => array(1=>'Desktop PCs',2=>'Games Consoles',3=>'Laptops'),
    3 => array(1=>'Drums',2=>'Woodwind',3=>'Guitars',4=>'Keyboard'),
    4 => array(1=>'Audi',2=>'BMW',3=>'Fiat',4=>'Ford',5=>'Honda'),
    5 => array(1=>'Cattle',2=>'Livestock',3=>'Chickens')
);
if( isset($_GET['categoryId']) AND array_key_exists($_GET['categoryId'],$databaseData) ) {
  $subcategories = $databaseData[$_GET['categoryId']];
  $html = '<option value="">Select...</option>';
  foreach($subcategories as $id => $subcategory) {
      $html .= '<option value="'.$id.'">'.$subcategory.'</option>';
  }
} else {
   $html = '';
}
echo $html;
?>

place this code into a file (maybe in an ajax folder) and test as you would on your localhost e.g.

http://localhost/ajax/getsubcategories.php?action=getSubcategories&categoryId=1

Let me know how you go on.

@paulkd i'm really sorry (and hope it doesn't sound stupid) but i honestly don't understand this code or what you're asking me to do.

Hi dhani09,

Can you copy the code into a php file and run it.

if you called it getsubcategories.php can you run it with the following at the end ?action=getSubcategories&categoryId=1

like this... getsubcategories.php?action=getSubcategories&categoryId=1

i did. But i just get a blank page with no output.

can you paste the actual url here? I know it's localhost.

Hi,

I've found the problem. I'm constantly learning too. You will be able to see the result in your browser by "view page source" Firefox displays the code fragment to the page, Chrome (and presumably other browsers) don't.

Here is some code which I think is what you are trying to set up. Let me know if I've misunderstood.

<form>
    <p>Categories <select id="categories" name="category">
        <option value="">Select...</option>
                    <option value="1">Motor Cycles</option>
                    <option value="2">Computing</option>
                    <option value="3">Musical Instruments</option>
                    <option value="4">Cars</option>
                    <option value="5">Farming</option>
            </select></p>
    <p>Sub-Categories <select id="subcategories" name="subcategory"></select>
</form>

yes it is. But i've been able to solve it using AJAX. I had to restructure the getData(), loadCategories() and updateSubcats() functions and it works fine now. But i really appreciate your help. I do. Here's the working AJAX code if you wanna take a look:

function getData(){
    var xhr = false;
    var sel1 = document.getElementById("categoriesSelect");
        var select1 = sel1.options[sel1.selectedIndex].text;  //This retreive the text value
    var select2 = document.getElementById("subcatsSelect").value;

    if (window.XMLHttpRequest) {

            xhr = new XMLHttpRequest();
        } 
        else {

            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", "?q1="+select1+"&q2="+select2, true);
            xhr.open("GET", "default.php?q1="+select1+"&q2="+select2, true);
            xhr.send(null);
        }
    }

    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],i);  

        }

        //getData();
    }

    function updateSubCats(catid){
        //alert(catid);
        //var catSelect = this;
        var catid = document.getElementById("categoriesSelect").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],subcats[catid][i]);
        }
        getData(); //Set to run for every category select change.
      }

The HTML code is the same.

Hi dhani09,

here's the final bit of jQuery code... added to the main selects page

 <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script>
$(document).ready(function(){

    $("#categories").on("change",function(){
        getSubcategories( $(this).val() );
    });

});

function getSubcategories(categoryId)
{
    var request = $.ajax({
        type: "GET",
        url: 'localhost:8888/getsubcategories.php',
        dataType: "html",
        data: {action:'getSubcategories', categoryId:categoryId}
    });

    request.fail(function(jqXHR, textStatus){
        alert( "ajax request failed: " + textStatus );
    });

    request.done(function(result){
        $("#subcategories").html(result);
    });
}
</script>

Respected sir how can i get value from ajax to dispaly page((input fields)

its really Helpfull

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.