Skip to content Skip to sidebar Skip to footer

Execute PHP Code When Selecting A Combobox Item

I have a static combobox in a php web page.I want when selecting an item from this combobox (example 'item 1') the php execute a SELECT statement to get the value of a field named

Solution 1:

You will need to use AJAX to do this. Here is a simple example:

HTML

Just a simple select box, for the purposes of this example.

<select id='items'>
    <option value='1'>Item 1</option>
    <option value='2'>Item 2</option>
    <option value='3'>Item 3</option>
</select>

JavaScript

I'm going to use jQuery here, you don't have to if you don't want to but it makes AJAX a whole lot easier.

The browser will listen for a change event on the select box and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.

$(document).ready(function() {
    $('#items').change(function() {
        $.ajax({
            type: 'GET',
            url: 'pageWithPhpCode.php',
            data: {
                itemID: $(this).val()
            },
            dataType: 'json',
            success: function(data) {
                // do whatever here
                console.log(data);
            }
        });
    });
});

PHP

Here I'm retrieving the data, JSON encoding it, and sending it back to the client with the appropriate MIME type. I'm not sure how you connect to your MySQL database, but I'm using PDO here.

Keep in mind that mysql_* functions are deprecated.

<?php
if(isset($_GET['itemID'])) {
    $db = new PDO();
    // ... connect to your database, however you do it

    $q = 'SELECT * FROM items WHERE id = :itemid;';
    $stmt = $db->prepare($q);
    $stmt->bindValue(':itemid', $_GET['itemID'], PDO::PARAM_INT);
    $stmt->execute();

    $output = $stmt->fetchAll(PDO::FETCH_ASSOC);

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($output);
}

Post a Comment for "Execute PHP Code When Selecting A Combobox Item"