pass associative array from php to javascript

14,816

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.

Share:
14,816
Abhimanyu1310
Author by

Abhimanyu1310

Updated on July 21, 2022

Comments

  • Abhimanyu1310
    Abhimanyu1310 almost 2 years

    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>
    
    • Admin
      Admin over 12 years
      Done research much? This is actually a somewhat common task (however, converting to JSON is not technically enough, "</script>" appearing in the JSON is a counter-example. JSON "works" simply because it is a proper subset of Javascript Literal Notation.
    • Paweł Adamski
      Paweł Adamski over 12 years
      Why all the downvotes? This is not a terrible question.
    • Joe the Person
      Joe the Person over 12 years
      Think its because its a Duplicate.
    • cdhowie
      cdhowie over 12 years
      That a duplicate question exists is not a valid reason to downvote. You downvote because a question is difficult to understand or poorly-worded, not because someone else asked the same thing already.
    • Gordon
      Gordon over 12 years
      @cdhowie If you hover over the downvote button you will see that it says: "this question does not show any research effort". Given that there is almost 4k results in the linked search above and there is multiple duplicates, this clearly warrants a dv. There should be even more results on Google for that. This question does not deserve any upvotes.
    • afuzzyllama
      afuzzyllama over 12 years
      What is the value of alert(v)?
    • Abhimanyu1310
      Abhimanyu1310 over 12 years
      function is not working. no output. I think this is because calling of the function is wrong. But I dont know what is wrong
    • Abhimanyu1310
      Abhimanyu1310 over 12 years
      @Gordon I have Google enough. I asked this question because I am passing the array using a function and the function is not working.
    • afuzzyllama
      afuzzyllama over 12 years
      @Abhimanyu1310 - are there any errors in the console? One of your document.getElementById(...).value might be returning null.
    • Arnaud Le Blanc
      Arnaud Le Blanc over 12 years
      @pst this is wrong, JSON allows to escape the / character for the purpose of escaping </script>, and json_encode does it. stackoverflow.com/questions/7217054/…
    • Abhimanyu1310
      Abhimanyu1310 over 12 years
      If I dont use json_encode($arrayname) then it works perfectly. But when I pass the array it doesn't. And no error on console.
    • afuzzyllama
      afuzzyllama over 12 years
      Please post your JSON string from your array.
  • afuzzyllama
    afuzzyllama over 12 years
    Thanks @cdhowie, I usually try to have complete code O_o
  • cdhowie
    cdhowie over 12 years
    No problem, just trying to make the code clearer. :) +1 too, this is the right approach.
  • Admin
    Admin over 12 years
    This is not very happy when "</script>" appears in the JSON. While JSON is a subset of JavaScript literals, not all JavaScript literals are valid in a <script> element (and I'm ignoring XHMTL entirely). I really wish there was a function designed just to facilitate this particular use-case with it's little caveats.
  • Abhimanyu1310
    Abhimanyu1310 over 12 years
    I am doing the same thing. json_encode function. But with a small difference, I am passing array of php to js by calling a function. And the function is not working. I just used alert() in the calling funcition to check if value is received. But nothing happened.
  • afuzzyllama
    afuzzyllama over 12 years
    Why would '</script>' appear in the JSON? I don't understand your comment
  • afuzzyllama
    afuzzyllama over 12 years
    @Abhimanyu1310 - Please post your code, I cannot debug code I cannot see
  • Abhimanyu1310
    Abhimanyu1310 over 12 years
    code<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> code <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);?>);">
  • Abhimanyu1310
    Abhimanyu1310 over 12 years
    sorry I dont know how to post the code more clearly. New on Stackoverflow.
  • Abhimanyu1310
    Abhimanyu1310 over 12 years
    code <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>
  • afuzzyllama
    afuzzyllama over 12 years
    post it in your question
  • Arnaud Le Blanc
    Arnaud Le Blanc over 12 years
    This is perfectly safe, even if the string contains </script>. PHP's json_encode escapes the / for this purpose.
  • Admin
    Admin over 12 years
    @arnaud576875 Corrected downvote. What about ]]> which could occur in XHTML?
  • Arnaud Le Blanc
    Arnaud Le Blanc over 12 years
    That may (assuming that the document is really parsed as XML) close the CDATA node, not the script element. That may cause a XML syntax error if the document is parsed as XML (nobody send an xml content-type).