2

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? My javascript:

<script type = "text/javascript">
function getData(str){
var xhr = false;
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", "/display-product.php?q="+str, true);
        xhr.send(null);
    }
}
</script>

The dropdown list in display-product.php:

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

The div to display the selected item:

<div class="product_directory" id="div1"></div>

I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.

UPDATE: i was able the figure out the source of the problem: 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 in the select list . 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. I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().

4
  • why are you not using JQuery? Commented May 2, 2013 at 20:55
  • 4
    Nothing wrong with not using jquery Commented May 2, 2013 at 21:01
  • Try to listen what your browser really send to a server when onChange event triggered. Take a look please, does variable q send and contain something? This could help localize a trouble. Commented May 2, 2013 at 21:09
  • Could you add the display-product.php full code ? Commented May 2, 2013 at 21:10

2 Answers 2

2

It seems your code is retrieving the value on the select. But it fails on your function.

I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.

...

 xhr.open("GET", "display-product.php?q="+str, true);

...

EDIT: full working code...

<script type = "text/javascript">
function getData(str){
var xhr = false;
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", "display-product.php?q="+str, true);
        xhr.send(null);
    }
}
</script>

<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<div id="div1"></div>

... on display-product.php

echo $_GET['q'];

Try this for the edited part of your question.

And this other to make it work together.

Hope this helps.

Sign up to request clarification or add additional context in comments.

11 Comments

that didn't work either Luigi.. were u able to get the value of q using $_GET['q']? or it just worked without the slash on your end?
Mine doesn't work and the code is pretty much the same.. i wonder what's wrong
... It's the same, i took it from you :) The only difference is that slash I mentioned you before. Also, verify the html that is been generated in PHP.
I figured out the source of the problem but not the solution. I've made an update to the question. Do you have an idea about what's wrong?
yea Luigi but the selected content doesn't get displayed even with your proposed method. But when i manually put the options in <options></options>. The selected content displays fine. I don't know why.
|
1

You can use a this possible solution with JQuery:

  1. Add the attribute "id" in option tag in php code and remove onChange function:

    echo "<select id='mySelect' title='Select one' name='selectcat'>";

  2. Add Jquery File JQuery 1.9.1 and add the javascript HTML tag

  3. Put before close tag body:

    $(document).ready( function() {
    $('#mySelect').change(function(){

      var $selectedOption = $(this).find('option:selected');
      var selectedLabel = $selectedOption.text();
      var selectedValue = $selectedOption.val();
      alert(selectedValue + ' - ' + selectedLabel);
      $('.product_directory').html(selectedValue + ' - ' + selectedLabel);
       $.ajax({
        type:"POST",
        url:"display-product.php",
        data:selectedValue OR selectedLabel,
        success:function(response){
            alert('Succes send');
        }
      })
      return false;
    });
    

    });

  4. Read in php:

    echo $_POST['selectedValue'];

    or

    echo $_POST['selectedLabel'];

5 Comments

thanks but i don't understand what you mean; plus the jquery 1.9.1 is too huge a file..
"Put after close tag body the next script:" Do you mean after the </body> tag?
Refresh the page, Im modified the text, excuse me, my english it's so bad. Caution in ajax send, in data:selectedValue OR selectedLabel, choose only one
I haven't used jquery before. How do i implement step2 i.e: "Add Jquery File JQuery 1.9.1 and add the javascript HTML tag"
Go to the link I wrote in my answer and press Ctrl + and Ctrl+c after, you've got the cilpboard .. creates a jquery.js file in the root of your project, and paste the code .. now from the html file make the call: <script type="text/javascript" src="js/jquery.js"></script> that line goes before the script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.