Connecting Tech Pros Worldwide Forums | Help | Site Map

parsing php array to javascript

Member
 
Join Date: Nov 2008
Posts: 41
#1: 4 Weeks Ago
Am trying to parse a php array into javascript but i found that only one element of the array was present in the javascript array. here is my code code
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include("../../connect.php");
  3. $qry="select * from stock";
  4. $rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
  5. while($row=mysql_fetch_assoc($rst)){
  6.     $item=$row['item'];
  7.     $list[$item]=$row['price'];
  8. }
  9. foreach($list as $key =>$value){
  10.     echo $key."-";
  11.     echo $value."<br/>";
  12. }
  13. echo $list['coke'];
  14. ?>
  15. <script type="text/javascript" language="javascript">
  16. list = new Array("<?php echo $list[$item]; ?>")
  17. alert(list);
  18. </script>
  19.  
the foreach loop worked just fine printing all the keys and values in the database but in the process of parsing it i seem to be doing something wrongly
cos the alert is only printing the value the last key "5000"

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#2: 4 Weeks Ago

re: parsing php array to javascript


the problem is that a Javascript array is somewhat different from a PHP array. a Javascript array uses only numeric values as key. or put in other words, there is no such thing as an associative array in Javascript.

an associative array in Javascript is called: object. you have several options to define a (standard) object
- using the Object Literal
Expand|Select|Wrap|Line Numbers
  1. var obj_name = {
  2.     key1 : value1,
  3.     key2 : value2
  4. // etc.
  5. }
- create an object with “new”, applicable if you have a predefined set of keys
Expand|Select|Wrap|Line Numbers
  1. function MyObject(value)
  2. {
  3.     this.key = value;
  4. }
  5. var obj_name = new MyObject("a value");
- create a new empty object and append the values
Expand|Select|Wrap|Line Numbers
  1. var obj_name = new Object;
  2. obj_name.key1 = value1;
  3. obj_name.key2 = value2;
  4. // etc.
and regarding the output. calling $list[$item] is exactly one value.
Member
 
Join Date: Nov 2008
Posts: 41
#3: 4 Weeks Ago

re: parsing php array to javascript


i think i uderstand the 1st and last options but the array is being generated by values from a table in the database and i have no control over the size of the array and worse i dont think javascript have the foreach loop equivalent
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#4: 4 Weeks Ago

re: parsing php array to javascript


Quote:

Originally Posted by freefony View Post

and worse i dont think javascript have the foreach loop equivalent

wrong.

nevertheless, it doesn’t matter. since PHP long finished execution when JavaScript starts, you have to print each and every key - value combination by PHP (using method 1 or 3 (2 was for completeness))
Member
 
Join Date: Nov 2008
Posts: 41
#5: 4 Weeks Ago

re: parsing php array to javascript


Expand|Select|Wrap|Line Numbers
  1. echo "<script languege='javascript'>";
  2. foreach($list as $key=>$val){
  3.  echo "var item=".$key;
  4.  echo "var price=".$val;
  5. }
  6. echo "</script>";
  7.  
Member
 
Join Date: Nov 2008
Posts: 41
#6: 4 Weeks Ago

re: parsing php array to javascript


is there any chance that would work?
gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,136
#7: 4 Weeks Ago

re: parsing php array to javascript


Quote:

Originally Posted by Dormilich View Post

Expand|Select|Wrap|Line Numbers
  1. var obj_name = {
  2.     key1 : value1,
  3.     key2 : value2
  4. // etc.
  5. }

wouldn't that be similar to:

Expand|Select|Wrap|Line Numbers
  1. echo 'var obj_name = '.json_encode($php_array);
  2.  
kind regards
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#8: 4 Weeks Ago

re: parsing php array to javascript


Quote:

Originally Posted by freefony View Post

is there any chance that would work?

nope, you’d end up redeclaring 2 variables

@gits: looks like that.
gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,136
#9: 4 Weeks Ago

re: parsing php array to javascript


i did ... and i thought ... even when i'm not a php-expert that for the current case:

Expand|Select|Wrap|Line Numbers
  1. echo 'var list = '.json_encode($list);
could do the job? it should create a string that is later on evaled by JavaScript as an object (or assoc array if you want to call it that) with all keys and values in the $list array?

kind regards
Member
 
Join Date: Nov 2008
Posts: 41
#10: 4 Weeks Ago

re: parsing php array to javascript


Hey the jason function is a powerful tool! but little problem tho i still cant get the javascript array.
Expand|Select|Wrap|Line Numbers
  1. //these two lines works perfectly
  2. $mylist=jason_encode($list);
  3. var_dump($mylist);
  4. //output: string(64) "{"coke":"70","Emzor Paracetamol BP":"2","Paracetamol BP":"5000"}" 
but the following codes return nothing what am i doing wrong?
Expand|Select|Wrap|Line Numbers
  1. echo "<script languege='javascript'>";
  2. echo "var mylist=".json_encode($list);
  3. echo "document.write(mylist)";
  4. echo "var data=eval(mylist)";
  5. echo "</script>";
  6.  
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#11: 4 Weeks Ago

re: parsing php array to javascript


1. you don’t have an Array
2. what do you expect document.write(mylist) to output?*

* from the JavaScript Point-of-View, it outputs the variable’s string representation (for object it’s the toString() method’s return value)

PS. had a look in Firebug, the object was created as desired
PPS. there’s a typo on line 1 and you really should use the type attribute there
didoamylee's Avatar
Newbie
 
Join Date: Nov 2008
Location: Köln , Deutschland
Posts: 15
#12: 4 Weeks Ago

re: parsing php array to javascript


Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2. var a = new Array('<?php echo implode("','",$php_array); ?>');
  3. </script>
  4.  
That should do the trick.
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#13: 4 Weeks Ago

re: parsing php array to javascript


Quote:

Originally Posted by didoamylee View Post

That should do the trick.

it doesn't. because the PHP array is associative and javascript arrays are always numeric.
Member
 
Join Date: Nov 2008
Posts: 41
#14: 4 Weeks Ago

re: parsing php array to javascript


Ok guys! i got working
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $qry="select * from stock";
  3. $rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
  4. while($row=mysql_fetch_assoc($rst)){
  5.     $item=$row['item'];
  6.     $list[$item]=$row['price'];
  7. }
  8. ?>
  9. <script type="text/javascript" language="javascript">
  10. var list=new Array('<?php echo json_encode($list); ?>');
  11. document.write(list);
  12.  
  13. </script>
  14.  
this suits my purpose and would solve a lot of problems i ve been facing with jscript and php arrays thanks to u guys
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#15: 4 Weeks Ago

re: parsing php array to javascript


but you know that you sacrifice your PHP array keys with this?

how to do print_r() in Javascript
Expand|Select|Wrap|Line Numbers
  1. var my_php_array = { //… } // from json_encode()
  2. my_php_array.toString = function()
  3. {
  4.     var str = "";
  5.     for (var key in this)
  6.     {
  7.         str += key+" => "+this[key]+"\n";
  8.     }
  9.     return str;
  10. }
  11. div.innerHTML = my_php_array;
Member
 
Join Date: Nov 2008
Posts: 41
#16: 3 Weeks Ago

re: parsing php array to javascript


even with the toString function above javascript still sees my php_array as just on element of the list array what can i do to solve that problem?
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,669
#17: 3 Weeks Ago

re: parsing php array to javascript


do not use new Array()
Reply