3

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>
Community
  • 1
  • 1
Abhimanyu1310
  • 71
  • 1
  • 1
  • 3
  • 3
    Done research much? This is actually a somewhat common task (however, converting to JSON is not technically enough, "" appearing in the JSON is a counter-example. JSON "works" simply because it is a proper subset of Javascript Literal Notation. –  Aug 27 '11 at 20:12
  • 4
    Why all the downvotes? This is not a terrible question. – Paweł Adamski Aug 27 '11 at 20:18
  • 2
    Think its because its a Duplicate. – Joe the Person Aug 27 '11 at 20:19
  • 1
    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. – cdhowie Aug 27 '11 at 20:20
  • 1
    @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. – Gordon Aug 27 '11 at 20:22
  • What is the value of alert(v)? – afuzzyllama Aug 27 '11 at 20:36
  • 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 Aug 27 '11 at 20:49
  • @Gordon I have Google enough. I asked this question because I am passing the array using a function and the function is not working. – Abhimanyu1310 Aug 27 '11 at 20:52
  • @Abhimanyu1310 - are there any errors in the console? One of your `document.getElementById(...).value` might be returning null. – afuzzyllama Aug 27 '11 at 20:58
  • 1
    @pst this is wrong, JSON allows to escape the `/` character for the purpose of escaping ``, and json_encode does it. http://stackoverflow.com/questions/7217054/pass-associative-array-from-php-to-javascript/7217312#7217312 – Arnaud Le Blanc Aug 27 '11 at 21:03
  • 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. – Abhimanyu1310 Aug 27 '11 at 21:04
  • Please post your JSON string from your array. – afuzzyllama Aug 27 '11 at 21:22

2 Answers2

10

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.

Community
  • 1
  • 1
afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
  • Thanks @cdhowie, I usually try to have complete code O_o – afuzzyllama Aug 27 '11 at 20:15
  • No problem, just trying to make the code clearer. :) +1 too, this is the right approach. – cdhowie Aug 27 '11 at 20:16
  • This is not very happy when "" appears in the JSON. While JSON is a subset of JavaScript literals, not all JavaScript literals are valid in a –  Aug 27 '11 at 20:23
  • 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. – Abhimanyu1310 Aug 27 '11 at 20:25
  • Why would '' appear in the JSON? I don't understand your comment – afuzzyllama Aug 27 '11 at 20:26
  • @Abhimanyu1310 - Please post your code, I cannot debug code I cannot see – afuzzyllama Aug 27 '11 at 20:27
  • `code` `code` – Abhimanyu1310 Aug 27 '11 at 20:33
  • sorry I dont know how to post the code more clearly. New on Stackoverflow. – Abhimanyu1310 Aug 27 '11 at 20:37
  • `code ` – Abhimanyu1310 Aug 27 '11 at 20:38
  • post it in your question – afuzzyllama Aug 27 '11 at 20:39
  • 1
    This is perfectly safe, even if the string contains ``. PHP's json_encode escapes the `/` for this purpose. – Arnaud Le Blanc Aug 27 '11 at 20:56
  • @arnaud576875 Corrected downvote. What about `]]>` which could occur in XHTML? –  Aug 27 '11 at 21:07
  • 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). – Arnaud Le Blanc Aug 27 '11 at 21:11
0

I always believed JSON were invented for this:

<script>
    var myArray = <?=json_encode($myArray)?>;
</script>

This will render like this:

<script>
    var myArray = {"key":"value","key2":"value2",...};
</script>

Safeness

This is perfectly safe for javascript, as JSON is a subset of the javascript syntax. This means that any JSON string can be treated as Javascript.

PHP's json_encode() is perfectly safe when embedding JSON in <script> tags too, because PHP escapes the / character:

json_encode('</script>');
=> "<\/script>"

So it's not possible to write </script>, which is the only way to escape a <script> tag. (Everything in a <script> tag is part of the script, it's not parsed as HTML.) JSON allows to escape the / for this purpose.

So no JSON string can escape a <script> tag.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194