1

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?

1
  • 1
    Why should you need Javascript to populate a dropdown with PHP values? Commented Aug 28, 2018 at 17:51

2 Answers 2

6

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>";
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Tbh I disagree on that since I have done that myself.
0

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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.