pass associative array from php to javascript

Abhimanyu1310 picture Abhimanyu1310 · Aug 27, 2011 · Viewed 13.9k times · Source

Possible Duplicate:
How to pass an array of strings from PHP to Javascript using $.ajax()?

I want to pass a associative array from php code to javascript code. Please help me. how do I do this ? Is JSON helpful in this matter? If yes then please provide a simple code for help. Thank you.

From comment below:
HTML + PHP code

<td> 
    <input type="text" style="width:70;" name="<?php echo $quantity;?>" id="<?php echo $quantity;?>" onkeyup="check_valid_range('<?php echo $itemName;?>','<?php echo $quantity;?>',<?php echo json_encode($product_inventory);?>);">
</td> 
<script type="text/javascript"> 
    function check_valid_range(product_field, quantity_field, inventory){ 
        var product = document.getElementById(product_field).value; 
        var quantity = document.getElementById(quantity_field).value; 
        var v = inventory[product]; 
        alert(v); 
    } 
</script>

Answer

afuzzyllama picture afuzzyllama · Aug 27, 2011

JSON is perfect:

<?php

$mySweetJSONString = json_encode($myAssocPHPArray);

?>
<script>
    var iWantThePHPArrayHere = <?php echo $mySweetJSONString; ?>;
</script>

User pst brought up these concerns:

  • "array("</script>") -- darn, just broke this "perfect" approach."
    It seems to work because (</script> => <\/script>):
    jsFiddle

  • "What about ]]> which could occur in XHTML?"
    The string is able to be transferred.
    jsFiddle


Update:

In regards to debugging the problem with the JS:
Are there any errors in the console? One of your document.getElementById(...) might be returning a null. Therefore the member value doesn't exist.