Yi Ming
Yi Ming

Reputation: 41

select option in php and mysql.. once option selected list down my sql database data

I been finding for long unable to search for it.. I have a dropdown select option call from mysql database.. I wanted when the user choose a employee from the option.. when selected.. it's list out the data from mysql database the employee data that is selected. here the code..

<select value="employee" selected="selected"> Select a employee</option>
  <?php
     $query = "SELECT * FROM users";
     $result = mysqli_query($link,$query);
     while ($row = mysqli_fetch_array($result)) {
        $fname = $row["first_name"];
        $lname = $row["last_name"];
        echo "<option value'" . $fname . " " . $lname ."'>" . $fname . " " . $lname . "</option>";
     }
 ?>
</select>

sorry i'm new to js.. how do I get the data from selected value?

Upvotes: 0

Views: 1350

Answers (2)

hacene abdessamed
hacene abdessamed

Reputation: 559

First of all edit your page and add jquery library

<select id="listEmployee" value="employee" selected="selected"> Select a employee</option>
      <?php
         $query = "SELECT * FROM users";
         $result = mysqli_query($link,$query);
         while ($row = mysqli_fetch_array($result)) {
            $fname = $row["first_name"];
            $lname = $row["last_name"];
            $id = $row["id"];
            echo "<option value'" .$id."'>" . $fname . " " . $lname . "</option>";
         }
     ?>
    </select>

Then you should listen to select change

$( "#listEmployee" ).change(function() {
  getSelectedEmplpyee();
});

Then create an ajax function that get informations about the selected employee

function getSelectedEmplpyee()
{
 var selectedId = $('#listEmployee').val();
$.ajax({
  type: "POST",
  url: "Controller.php",
  data: {selected: selectedId},
  success: function(data) {
    //display response
  },
  error: function(data) {
    // display error
  }
});
}

in controller.php read the id using

$id = $_POST['selected']

in controller.php run your select query and return result using echo , the result is stored in the variable data in your function getSelectedEmplpyee()

Upvotes: 1

Gulmuhammad Akbari
Gulmuhammad Akbari

Reputation: 2036

Try to do like this:

var selected_value = $('#your_select_id').val();
$.ajax({
  type: "POST",
  url: "your_url",
  data: {selected: selected_value},
  success: function(data) {
    //display response
  },
  error: function(data) {
    // display error
  }
});

Upvotes: 0

Related Questions