prog prog - 1 year ago 39
PHP Question

ajax dropdown box when a variable exists

I am trying to make an ajax call for the an dropdown box(dynamic)


  • when the variable
    $place
    is available it will make an ajax call and populate
    the dropdown box.



I am trying to pass the variable
$place
to
listplace.php
and encode it in json data and get the datalist values but not sure the encoded json file is correct

I just given a try and not sure below code works, please help.

Dropdown box

<select>
<option selected disabled>Please select</option>
</select>


Ajax call

<?php if(isset($_GET['place']) && $_GET['place'] !='') {?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $place ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
}
});
</script>
<?php } ?>


listplace.php

<?php
$sql = @mysql_query("select placename from employee where placename= '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}

Answer Source

Change your AJAX call to the following.

<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
    <script>
        $.ajax({
            type: "POST",
            data: {place: '<?= $_GET['place'] ?>'},
            url: 'listplace.php',
            dataType: 'json',
            success: function (json) {
                if (json.option.length) {
                    var $el = $("#name"); 
                    $el.empty(); // remove old options
                    for (var i = 0; i < json.option.length; i++) {
                        $el.append($('<option>',
                            {
                                value: json.option[i],
                                text: json.option[i]
                            }));
                    }
                }else {
                    alert('No data found!');
                }
            }
        });
    </script>
<?php } ?>

And your PHP to

<?php
$place = $_POST['place'];
$sql = @mysqli_query($conn,"select placename from employee where placename= '$place'");
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
    $rows[] = $r['placename'];
}
if (count($rows)) {
    echo json_encode(['option'=> $rows]);
}else {
    echo json_encode(['option'=> false]);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download