Jump to content

dynamically populate dropdown list based on MySQL response


Recommended Posts

I have a MySQL database that includes class name, class number, cost, description, and seats available. My current script has a dropdown menu for the class name. Based on the dropdown selection, the fields for class number, cost, and description change.

 

Now, I want to create a dropdown for the number of seats available. 

What I want to display is a dropdown list from 1 to number_of_seats_available (The database contains a number of seats available for each class.)

For instance, if there are 4 (four) seats left, the dropdown will show:

1
2
3
4

If there are 6 seats left, the dropdown will show 1-6.

I would normally do this with PHP with a foreach loop like: 

foreach(range(1,$seats_available) as $seats_dropdown){
echo "<option value='$seats_dropdown'>$seats_dropdown</option>\n";}

But this needs to be dynamic like the rest of the script, based on the class that is selected in the first dropdown.   I did some searching and couldn't find anything that matched my needs.  Anyone point me in the right direction?

 

Here's what I have so far for the rest of the form:

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// using jquery to apply an onchange event on the select element named class_drop_down
$('select[name="class_drop_down"]').on('change', function() {
// do an ajax request to get_class_details.php, passing selected the class name
$.ajax({
url: 'get-classes-for-registration-php-beta.php',
method: 'POST',
data: { class_name: $(this).val()},
dataType: 'json',
// this function is called with the response from the request
success: function(response) {
// make sure a error was not returned
if(response.error === undefined) {
// set values for class number and date fields as follows
$('input[name="course_number"]').val(response.course_number);
$('input[name="course_start_date"]').val(response.class_start_date);
$('input[name="class_start_time"]').val(response.class_start_time);
$('input[name="cost"]').val(response.cost);
$('#class_description').html(response.class_description);
$('#instructor').html(response.Instructor);

}
else {
// demo purposes only, output error message as an alert
alert(response.error);
}
},
});
});
</script>

Create a function and call it within the ajax response code. Here is some untested code:

 

In the ajax response code, something like:

 

updateSeatsAvail($('input[name="seatch"]'), response.seats);

 

 

 

function updateSeatsAvail(selObj, seats)
{
    selObj.empty(); //Remove current seat options
    for(var seat=0; seat<=seats; seat++)
    {
        selObj.append($("<option></option>").attr("value", seat).text(seat));
    }
}

if this portion of your ajax is basically just moving functionality from the server to the browser, for when javascript is enabled, you can practice DRY (Don't Repeat Yourself) programming. you already have server-side code that's producing the values, html, .... instead of outputting those values/html when the page is requested, output them as 'generic' json encoded data in the ajax response.

 

see the following example. code on your main page -

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Generic ajax - use server output to dynamically specify and populate elements in the dom without writing out code for each different thing</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            url: 'api.php',
            data: "",       //optional data to pass to api.php
            dataType: 'json',
            success: function(data)
            {
                var vals = data.val; // text and textarea values
                if(vals){
                    $.each(vals, function(key, value){
                        $(key).val(value);
                    });
                }
                
                var htmls = data.html; //inner html
                if(htmls){
                    $.each(htmls, function(key, value){
                        $(key).html(value);
                    });
                }
                
                var styls = data.styles; //css class name
                if(styls){
                    $.each(styls, function(key, value){
                        $(key).attr("class", value);
                    });
                }
                
                var sels = data.sel; // select/option - selected
                if(sels){
                    $.each(sels, function(key, value){
                        var v = value != '' ? true : false;
                        $(key).prop("selected", v);
                    });
                }
                
                var checks = data.che; // radio and checkbox - checked
                if(checks){
                    $.each(checks, function(key, value){
                        var v = value != '' ? true : false;
                        $(key).prop("checked", v);
                    });
                }
            }
        });
    });
});

</script>

</head>
<body>
    <form method='post' action='your_formaction.php'>
    <div id='seats'></div>
    <input type='submit'>
    </form>
    
    <button>DEMO button to Get JSON data. You can also just automatically load the data when the page is ready in the browser.</button>
</body>
</html>

example api.php code -

<?php

// the first array index is the 'type' that corresponds to the val, html, styles, ... in the javascript code
// the second array index is the jquery selector (typically an id selector '#id') that will be used by the javascript code

// output sample data -

// html example
$number_value = 3;
$content = "<select name='seat'>";
foreach(range(1,$number_value) as $value){
    $content .= "<option value='$value'>$value</option>\n";
}
$content .= "</select>";
$array['html']['#seats'] = $content;

// val/value example
$array['val']['input[name="course_number"]'] = $course_number; // from wherever you are getting the course number

echo json_encode($array);

this method can replace your existing .val(), .html() usage. i have included one .val() example that should work with your existing page.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.