简体   繁体   中英

How come values from my php dont populate in select-option

code to call function:

<select id="selectWarrior_1" name="warrior_1"  onclick="return selectWarriors()">
                    <option  selected="selected">----Select----</option>
                </select>

code of the function:

function selectWarriors() {
        $.ajax({
            url: "display_warriors.php",
            datatype:"json",
            success: function(data) {
                var toAppend = '';
                if(typeof data === "object"){
                    for(var i=0;i<data.length;i++){
                        var warrior = data[i];
                        toAppend += '<option>'+data[i]['warrior_name']+'</option>';
                    }
                    $("#selectWarrior_1 select").append(toAppend);
                }
            }
        });
        return false;
    }

Code of my php:

    <?php
header("Content-Type: application/json");

include 'functions/class.php';

$db = new DB();

$result = $db->getWarriors();

$warriors = array();

foreach($result as $names){
    $warriors[] = $names;
}
echo json_encode($warriors);
?>

How can I fix this? Why its not populating my select-option i checked my json and it has values.

Forgive the spacing, but I would actually just use jquery and not confuse ourselves with passing between functions (which can cause problems later if you are re-populating content asynchronously).

$(function(){
  $('#selectWarrior_1').bind('click',function(){
        if ( $(this).data('warriors-loaded') ) { return; }
        var self = $(this);
        $.ajax({
            url: "display_warriors.php",
            datatype:"json",
            success: function(data) {
              if (! typeof data == 'object') return false;
              $.each(data, function(i,e) {
                self.append( $('<option>' + e['warrior_name'] + '</option>') );
              }
              self.data('warriors-loaded',true);
            }
        });
  });
});

Well

input type select has no onclick event. Use onChange or onFocus event instead. Also you dont want to use return while calling the function. In your scenario it seems pretty useless to use return . Also watch the selector you have used.

Your selector is incorrect

Change $("#selectWarrior_1 select")

To $("#selectWarrior_1")

You need to treat data as a json object:

function selectWarriors() {
    $.getJSON('display_warriors.php', function(data) {
        var toAppend = '';
        $.each(data, function(key, val) {
            toAppend += '<option>'+val+'<\/option>';
        });
        $("#selectWarrior_1").append(toAppend);
    });
}

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