473,390 Members | 1,100 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,390 software developers and data experts.

parsing php array to javascript

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>
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"
Oct 28 '09 #1
16 9258
8,658 Expert Mod 8TB
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.
Oct 28 '09 #2
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
Oct 28 '09 #3
8,658 Expert Mod 8TB

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))
Oct 28 '09 #4
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>";
Oct 28 '09 #5
is there any chance that would work?
Oct 28 '09 #6
5,390 Expert Mod 4TB
wouldn't that be similar to:

Expand|Select|Wrap|Line Numbers
  1. echo 'var obj_name = '.json_encode($php_array);
kind regards
Oct 28 '09 #7
8,658 Expert Mod 8TB
nope, you’d end up redeclaring 2 variables

@gits: looks like that.
Oct 28 '09 #8
5,390 Expert Mod 4TB
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
Oct 29 '09 #9
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>";
Oct 29 '09 #10
8,658 Expert Mod 8TB
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
Oct 29 '09 #11
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2. var a = new Array('<?php echo implode("','",$php_array); ?>');
  3. </script>
That should do the trick.
Oct 29 '09 #12
8,658 Expert Mod 8TB
it doesn't. because the PHP array is associative and javascript arrays are always numeric.
Oct 29 '09 #13
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);
  13. </script>
this suits my purpose and would solve a lot of problems i ve been facing with jscript and php arrays thanks to u guys
Oct 30 '09 #14
8,658 Expert Mod 8TB
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;
Oct 30 '09 #15
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?
Nov 3 '09 #16
8,658 Expert Mod 8TB
do not use new Array()
Nov 3 '09 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Sandman | last post by:
Hello I have been trying to wrap my head arouns this, but I can't seem to get it to work the way I want it to. Could someone helpful please tell me how I get this: <function>...
by: Sven Neuberg | last post by:
Hi, I have been handed the task of updating and maintaining a web application, written in ASP and Javascript, that takes complex user inputs in HTML form and submits them to server-side ASP...
by: ralphNOSPAM | last post by:
Is there a function or otherwise some way to pull out the target text within an XML tag? For example, in the XML tag below, I want to pull out 'CALIFORNIA'. ...
by: Marc van Boven | last post by:
I'm stuck with the following problem: My nusoap-client calls a server-function giveCombination(). The function giveCombination should return something like array( => array( 'a_id' => 6,...
by: djdave | last post by:
My problem is that i need an algorithm parse parse HTML. For an HTML page, my script has to parse all tags to get all forms values, even if there is frame, iframe, ... How can i do such a script ?...
by: Paulers | last post by:
Hello, I have a log file that contains many multi-line messages. What is the best approach to take for extracting data out of each message and populating object properties to be stored in an...
by: Aaron | last post by:
I'm trying to parse a table on a webpage to pull down some data I need. The page is based off of information entered into a form. when you submit the data from the form it displays a...
by: Jasper | last post by:
Hi, Maybe this is off-topic, but perhaps you can help. I'm looking for ideas on how to parse a data file. I dont know XML but I know it parses data in text format. I have a structured data...
by: Philip Semanchuk | last post by:
On Oct 12, 2008, at 5:25 AM, S.Selvam Siva wrote: Selvam, You can try to find them yourself using string parsing, but that's difficult. The closer you want to get to "perfect" at finding URLs...
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.