1

I need to get data from the database with ajax and put that data in the 'select' tag. I need to have every name in a different 'option'... View the code:

Index.php:

<label>Select:</label>
<select id="users"></select>

JS:

$(document).ready(function() {
setInterval(function() {
    $.get("frombase.php", function(data) {
        data = JSON.parse(data);
        for (var id in data) {
            $("#users").empty();
            $("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
        }
    });
}, 1000);

});

And frombase.php:

$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);

$name = array();

while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));

mysqli_close($db);

Look at the result (I do not need this)

enter image description here

(My english is not good, because I use Google Translate)

3
  • 2
    Just do echo json_encode($name);. There's no need to put it in another array. Or if you want to keep it as is, then in your JS, do: for (var id in data.name]) and then + data.name[id] + . Commented May 6, 2018 at 18:01
  • Or change JS loop to for (var id in data.name) {. Note however is not good practice to is for in loops on arrays Commented May 6, 2018 at 18:03
  • 1
    You should probably also call $("#users").empty() before the loop. If it's in the loop as it is now, it will empty the select box on each iteration and you'll only end up with the last name. Commented May 6, 2018 at 18:05

1 Answer 1

1

I would do in this way...

JS:

        $(document).ready(function() {
            $.ajax({
                url :'frombase.php',
                type: "POST",
                dataType: "json",
                success : function(data){
                    $("#users").empty();
                    $(data['options']).each(function(k,v){
                        $("#users").append("<option value='"+ v['id'] +"'>"+ v['name'] +"</option>");
                    });
                },
                error:function(){
                    alert('Error of server comunication');
                }
            });
        });

PHP:

    $db = 'YOUR CONNECTION';
    $query = $db->prepare("SELECT id,name FROM users");
    $query->execute();        
    $query->bind_result($id,$name);

    while ($query->fetch()) {
        $result[] = array('id'=>$id,'name'=>$name);
    }
    $root['options'] = $result;
    $root = json_encode($root);     
    $db->close();
    echo $root; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.