简体   繁体   中英

Load MySQL data without Refresh Webpage

I try to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database. This is my table : 在此处输入图片说明

I hope, if i select a different fruit from the first selection, it will change the available varieties in the second select.

According to my script, i'm not able to get corresponding available varieties into the second select, what wrong on my script.

<form>
Fruit:
<select name="name" id="fruitName">
    <option>Apple</option>
    <option>Banana</option>
    <option>Orange</option>
    <option>Pear</option>
</select>
Variety:
<select name="variety" id="fruitVariety">
</select>
</form>

<script>
function populate() {
    $.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
    var select = $('#fruitVariety');
    var options = select.attr('options');
    $('option', select).remove();
    $.each(data, function(index, array) {
        options[options.length] = new Option(array['variety']);
    });
});
}

$(document).ready(function() {
populate();
$('#fruitName').change(function() {
    populate();
});
});
</script>

and this is my varities.php script

$result = array();
$fruitName = $_GET['fruitName'];
$res=mysql_query("SELECT variety FROM fruit WHERE name = '$fruitName' ORDER BY variety");
while ($row=mysql_fetch_array($res)){ 
    array_push($result, array('variety'=>$row['variety']));
}
echo json_encode(array('result'=>$result));

Please any suggestions?

Try the following function

function populate() {
    $.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
    var select = $('#fruitVariety');
    var options = select.empty();//empty the select box
    $.each(data.result, function(index, array) {//don't forget you have a result array
        select.append('<option value="'+array.variety+'">'+array.variety+'</option>');//append the option elements
    });
});
}
Make 2 separate tables,one for the fruits and another for the variety. Id of tbl_fruits will be a foreign key in tbl_variety.

1)First get all fruits and store the results in $fruits.

Therefore, first select will be like:

<select name="name" id="fruitName">
    <?php foreach($fruits as $fruit): ?>
          <option value="<?=$fruit['id']?>"><?=$fruit['name']?></option>;
     <?php endforeach; ?>
</select>

Then you can populate the 2nd dropdown using ajax:

<select name="variety" id="fruitVariety">
</select>


<script>
var id=$('#fruitName').val();
            $.ajax({  // first call will get the list as per the initial value of the fruit list when the page loads
                url:"get_variety.php",  
                method:"POST",  
                data:{initial:id},  
                dataType:"html",  
                success:function(data)              
                {  

                     $('#fruitVariety').html(data);  
                }  
           });


        $('#category').change(function(){  
           var id = $(this).val();


           $.ajax({  // this will be triggered whenever you select a different value from the fruits list
                url:"get-variety.php",  
                method:"POST",  
                data:{id:id},  
                dataType:"html",  
                success:function(data)              
                {  
                     $('#fruitVariety').html(data);  
                }  
           });
</script>

And in get-variety.php:

Check if $_POST['initial'] or $_POST['id'] is set and fire query accordingly:
$initial=$_POST['initial'];

$results= After executing('SELECT * FROM tbl_variety WHERE fruit_id="'.$initial.'"');

foreach ($results as $result) {
     echo '<option value="' . $result["id"] . '">'.$result["variety"].'</option>';
    }

Similary, run the query for the other POST variable.

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