Update text depending on option selected

I’ve got a drop down menu that is used to select different cd’s by a musician. That is done using this:

<select id="opt" name="opt" class="input_select" style="width: 150px;">
                        <?php foreach( $musician as $key=>$value ) { ?>
                        <option value="<?php echo $value['id'] ?>"><?php echo htmldisplay( $value['name']  ) ) ?></option>
                        <?php } ?>
                      </select>

I want different things to be shown depending on the option selected. I’m using this to choose what is shown, but that only works once.

				  <?php
            if( is_array( $musician ) ) {
              echo getcdtstock( $musician[0]['id'] );
            } else {
              switch( $cds_all[$dynaload]['stock_status'] ) {
                case 1: echo "<input class="input_button input_basket input_green" type="submit" value="Add to basket" />"; break;
                case 3: echo "<span style=\"color: #bfbfbf;\">Sorry, this cd is temporarily out of stock</span>"; break;
                case 4: echo "<span style=\"color: #cc2a41;\">Sorry we no longer stock this cd</span>"; break;
              }
            }
          ?>

I want it to change when different cd’s are selected but don’t know how to change that.

I’d be extremely grateful for any help with this. I know I need to use JavaScript but don’t know too much about it.

It sounds like an ajax request will be of most benefit to you here. This is where a request is made to the server (with the musician key and selected album) and the response from the server is then used to update part of the page.

Yes that sounds exactly what I need. Sorry to be dumb but how do I do that? I’ve not used Ajax before.

Are you using any kind of library like jQuery? If so, there are easy ways to do it, as can be seen in this article on how to use jQuery’s $.ajax() function

Thanks I’ll have a look at that, I do know that we’ve got jQuery. Thanks

Well in that case, have your "add to basket " code in a separate PHP file so that it can be called on an as-needed basis. Here’s an example that I’ve put together with two of Madonna’s albums:

stock_status.php

<?php
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING);

function stock_status($id) {
    $cds_all = array(
        "9c0d400c" => array("stock_status" => 3),
        "c90f4010" => array("stock_status" => 1)
    );
    if (empty($cds_all[$id])) {
        // use first id in the array
        $id = key($cds_all);
    }

    switch( $cds_all[$id]['stock_status'] ) {
        case 1: echo '<input class="input_button input_basket input_green" type="submit" value="Add to basket" />'; break;
        case 3: echo '<span style="color: #bfbfbf;">Sorry, this cd is temporarily out of stock</span>'; break;
        case 4: echo '<span style="color: #cc2a41;">Sorry we no longer stock this cd</span>'; break;
    }
}

echo stock_status($id);
?>

You would use the id value to query the database for the appropriate album details. You’ll also see that I’ve also told it that if the id can’t be found, to default to the first one in the list.

Note: Those id values are the real CDDB values for some of Madonna’s albums.

If you make the following request:
http://www.example.com/stock_status.php?id=c90f4010

You should get back a response (make sure it’s your servers domain instead of example.com), such as:
"<input class="input_button input_basket input_green" type="submit" value="Add to basket" />"

I’ve used the stock_status.php file with your existing PHP code by including it inside a span called “stockStatus”.

index.php

<?php
$musician = array(
    array("id" => "9c0d400c", "author" => "Madonna", "name" => "Confessions on a Dance Floor"),
    array("id" => "c90f4010", "author" => "Madonna", "name" => "MDNA")
);
function htmldisplay($value) {
    return htmlentities($value);
}
?>

<select id="opt" name="opt" class="input_select" style="width: 150px;">
    <?php foreach( $musician as $key=>$value ) { ?>
    <option value="<?php echo $value['id'] ?>">
    <?php echo htmldisplay( $value['name']  ) ?>
    </option>
    <?php } ?>
</select>

<span id="stockStatus">
<?php include("stock_status.php"); ?>
</span>

Here’s some example JavaScript using jQuery that can then make use of that stock_status.php script.

function updateStockStatus(status) {
    $('#stockStatus').html(status);
}
 
$('#opt').on('change', function () {
    var id = this.value;
    $.ajax('stock_status.php', {
        data: {"id": id},
        success: function (response) {
            updateStockStatus(response);
        }
    });
});

You can should put the JavaScript in a separate file and use a few script tags at the end, just before the body tag, to get things going.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="updateStockStatus.js"></script>

That’s easy with jQuery.
First, bind onChange listener to select and send request with selected value using POST:

<script>
    $(document).ready(function(){
        $('select#opt').on('change', function(){

            //get selected id
            var id = $(this).val(); 
            
            // send request
            $.post('script.php', {musician_id: id}, function(result){
                // in result variable we'll get answer from
                // the PHP as a JSON object:
                if (result.message == "ok"){
                    // if ok show "add to cart" button
                    // and hide span with message
                    $('.input_basket').show();
                    $('.message').hide();
                } else { 
                    $('.input_basket').hide();
                    $('.message').html(result.message).show();
                }
            }, 'json');

        });
    });
</script>

script.php:

$id = $_POST['musician_id'];
$result = array();

// .. get cds list from db ...
$cds_all = getFromDatabaseOrWhatever();

switch( $cds_all[ $id ]['stock_status'] ) {
    case 1: $result['message'] = "ok"; break;
    case 3: $result['message'] = "out of stock"; break;
    case 4: $result['message'] = "not in stock"; break;
    default: $result['message'] = "unknown cd";
};

echo json_encode($result); exit;

Thank you so much, that looks exactly what I’m after :slight_smile:

Could I have the code in the script.php in the same file and call it that way?

The reason I ask is because there’s lots of calculations that are done to get the cd’s. Various tables in the db are queried etc.

Sure you can place that code in the same file.
But I think it will be much better to move “calculations” code into external file instead.
That will allow you to implement separated controllers (scripts) for different requests (regular GET, AJAX and any other) without mixing them all in a huge single file.

In my example:

$cds_all = getFromDatabaseOrWhatever();

that function can be defined in external file which you’ll include at the beginning

if I was to include it in the same file how would I get it to work, at the moment you say that $.post('script.php', {musician_id: id}, sends the request.

You can do that in many ways.

For example you can add another POST variable, say “is_ajax” in request:

$.post('your-script.php', {musician_id: id, is_ajax: 1}, function(result){

and check it in your script:

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

    // prepare response...
    $id = $_POST['musician_id'];
    $result = array();

    switch( $cds_all[ $id ]['stock_status'] ) {
        case 1: $result['message'] = "ok"; break;
        case 3: $result['message'] = "out of stock"; break;
        case 4: $result['message'] = "not in stock"; break;
        default: $result['message'] = "unknown cd";
    };
    
    //render response and quit ..
    echo json_encode($result); exit;

}

of course that block should be placed after the code that prepares your $cds_all data.

Thank you :slight_smile:

but before any other output, that’s important
you should print only JSON when you receive AJAX request

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.