0

I have this HTML/PHP Code that populates a select box

<select name="customerbilling_productname" id="mySelectBox" onchange="changeValue(this.value);" style="width:120px;">
    <option value="">Please Choose</option>
    <option value="Type Custom">Type Custom</option>
    <?php
    $json_array = array();
    $stmt = $pdo_conn->prepare("SELECT * from prices ");
    $stmt->execute(array());
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach($records as $result2) {
        $product = $result2["product"];
        $json_array[$product] = $result2['retail'];
        echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
    }
    json_encode($json_array, JSON_FORCE_OBJECT); 
    ?>
    </select>

And this JS Code:

<script>
var json = <?php echo $json_array; ?>;
function changeValue(myValue) {
    document.getElementById("customerbilling_unitprice").value = json[myValue];
}
</script>

So when i select an option from the drop down, it should populate the customer billing_unitprice text input to have the value from the retail column in the database

when i select an option from the drop down, it is showing undefined in the text input and not the value in the database

2 Answers 2

2

You are encoding the json like this:

json_encode($json_array, JSON_FORCE_OBJECT); 

but you aren't assigning it to anything.

So, do this:

$json_str = json_encode($json_array, JSON_FORCE_OBJECT); 

Then update your javascript like this:

var json = JSON.parse('<?php echo $json_str; ?>');

The reason why I am doing JSON.parse() is because PHP's json_encode returns a json string. You then need to parse this into an object/array in javascript.

Sign up to request clarification or add additional context in comments.

Comments

0

try to change this:

var json = <?php echo $json_array; ?>;

to this:

var json = '<?php echo $json_array; ?>';

1 Comment

How will this work? here, wouldn't $json_array be an actual php array? so the javascript variable will end up like this: var json = 'Array';

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.