user2334436
user2334436

Reputation: 939

Using PHP array and JS to populate values into dropdown

I'm using PHP and JS to get data from SQL table then populate the result into a dropdown list.

My code is working fine but I'm having a problem using the return output as an array for JS.

In my PHP part of the code, I'm formatting the output into JSON encode'

    echo $js_array = json_encode($Unit_tenants);
    // output is ["1","2","3"]

Now I want to use the return value of this output with JS to populate those values into a dropdown list with values 1,2,3

My JS code

<script>

  $(document).ready(function(){
            $('#ddlUnitNo').change(function(){
                //Selected value
                var inputValue = $(this).val();

                //Ajax for calling php function
                $.post('list.php', { dropdownValue: inputValue }, function(data){


                    //do after submission operation in DOM

                    var select = document.getElementById("selectNumber"); 
var options = data; 

// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
                         });
            });
        });
</script>

The problem is in var options = data because this is being recognized as a string rather than an array with multiple values. any idea how to fix this?

Upvotes: 1

Views: 1522

Answers (2)

jdubu423
jdubu423

Reputation: 425

Javascript wont accept the php array as an array. You need to convert it to an array, or in this case a JSON object.

Try the following:

in php:

return json_encode($data);

in javascript:

var options = JSON.parse(data);
// Populate list with options:
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
 }

Upvotes: 6

Padmanabhan
Padmanabhan

Reputation: 158

Try this, the PHP way

   <?php  $js_array = ["1","2","3"]; ?>

    <select name="someName" onChange="">
    <option value="" selected>Select One</option>

   <?php    for($k=0, $< count($js_array); $k++){ ?>

    <option value="<?php echo($js_array[$k] ?>"><?php echo($js_array[$k] ?></option>

    <?php } ?>

    </select>

Upvotes: 0

Related Questions