user5723483
user5723483

Reputation:

change a drop list according to another with data given from MySQL

I need to get some data inside a drop list, and then after selecting a specific type, I need the other drop list to get specific type of values from MySQL too.

I have this link that works properly, but I can't modify it to accept values from my database.

My column of the first drop list is:

Refrigerator

Microwave

TVs

Heaters

And then, when I click on one of them, I will get a new data selected into my other drop list, like if I choosed TVs, second drop list will bring new data like:

LG

SAMSUNG

VESTEL

...

Any help is appreciated.

Upvotes: 0

Views: 61

Answers (1)

Gary Holiday
Gary Holiday

Reputation: 3582

You need to use something like AJAX,

Jquery/Ajax code

$(document).ready(function() {

  $('#id-of-the-first-drop-list').change(function() {

    // get the form information
    // this can be done in many ways but we are going to put the form 
    // data into a data object
    var formData = {
      'selectedValue' : $('#id-of-the-first-drop-list').val()
    };

    // send the data via Ajax
    $.ajax({
      type      : 'POST', // the method we want to use to send the data
      url       : 'get-data-from-database.php', // the url where we want to 
                                                // send the data
      data      : formData, // the data object we created
      dataType  : 'json', // what type of data we want to get back
      encode    : true
    })
      // execute function when data has been sent and server
      // code is processed
      .done(function(data) {
            // HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
            // I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
            // data[0], data[1]... TO GET THE VALUE

            // I got this from somewhere else on stackoverflow
            var myOptions = {
                val1 : data[0],
                val2 : data[1]
            };
            var mySelect = $('#id-of-the-second-drop-list');
            $.each(myOptions, function(val, text) {
              mySelect.append(
                $('<option></option>').val(val).html(text)
              );
            });
      });

  });

});

Now here is the server side code that will get the data from the database

PHP code

<?php
    $data = $_POST['selectedValue'];

    // Connect to database
    // Use the data to get the new information
    $query = "SELECT * FROM table_name WHERE column_name = '$data'"
    // MySQL
    $results = mysql_query($query);

    $data = array();
    $i = 0;
    while($row = mysql_fetch_array($results)) {
         data[i] = row['column_name'];
         $i++;
    }

    echo json_encode($data);
?>

This code wasn't tested and may have errors but this is the general idea. I hope it helps.

Upvotes: 2

Related Questions