简体   繁体   中英

PHP jQuery dynamically populated SELECT

Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...

$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");

I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.

My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.

I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .

You need ajax.

When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).

You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.

Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.


JAVASCRIPT PART:

  1. Bind event to the first dropdown
  2. Get value of the option selected in the dropdown
  3. Make ajax request

Here is some example code:

 var parameters='value_selected='+value_dropdown;
 jQuery.Post({
       url: '/destiny_when_I_process',
       data: parameters, 
       success: func_callback

 });
//here you can imagine a pause, because PHP is processing the data you send by post
//....  
//....
//this part is executed when php send the information 
function func_callback(response_from_php){
       jQuery('#second_dropdown').html(response_from_php); 
}

PHP PART:

  1. get value from POST
  2. access database using this value
  3. echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.

JAVASCRIPT PART (SECOND PART)

  1. in the callback function, you receive the response data via the first parameter
  2. Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)

for the secondary drop down, yes, you'll need some ajax.

You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.

Using jquery and php you'll need a few thing.

A php file to get the result and return the options. (let say getStaff.php)

<?php 
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);

//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);

//split the data in the array
$staffs=array();
    while ($assoc = mysql_fetch_assoc($r)) {
          //Varialbe = $assoc['colum_name'];
          $staff->id=$assoc['id'];
         $staff->name=$assoc['name'];
        //and so on for each colum in your table.
        array_push($staffs, $assoc);
   }

//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>

In you first select, add

onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"

and add an id to your second select (staff_select) in this ecample.

As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilà!

Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.

Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....

Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.

And thanks to everyone here.

PHP to build for the first :

function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
    $opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}

HTML for the two elements:

<label for="AgencyId">Client/Agency:</label>
    <select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
        <?php echo agency_select(); ?>
    </select>

<label for="Contact">Contact: </label>
    <select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
        <option value="">----Select Client/Agency----</option>
    </select>

AJAX file:

if(isset($_POST['AgencyId'])) {

include('../include/dbase.php');

$option = '<option value="">----Select Contact----</option>';

$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ?  AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}

echo $option;
}

jQuery:

$(document).ready(function () {
    update_contacts();
});

function update_contacts() {
$('#AgencyId').change(function() {
    $('#Contact').fadeOut();
    $('#loader').show();

$.post('../ajax/ajax_contact_select.php', {
        AgencyId: $('#AgencyId').val()
        }, function (response) {
        setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
        });
        return false;
    });
}

function finishajax(id,response) {
    $('#loader').hide();
    $('#'+id).html(unescape(response));
    $('#'+id).fadeIn();
}

i'll try to help you as much as i can a explain it.

mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set. This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.

So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:

    while ($assoc = mysql_fetch_assoc($r)) {
          //Varialbe = $assoc['colum_name'];
          $stores->id=$assoc['id'];
         $stores->name=$assoc['name'];
        //and so on for each colum in your table.
        array_push($stores, $assoc);
   }

Then you can export it as you want. in you case would be something like

foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";

I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM