473,805 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

parsing php array to javascript

59 New Member
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"
Oct 28 '09 #1
16 9305
Dormilich
8,658 Recognized Expert Moderator Expert
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
freefony
59 New Member
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
Dormilich
8,658 Recognized Expert Moderator Expert
@freefony
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))
Oct 28 '09 #4
freefony
59 New Member
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.  
Oct 28 '09 #5
freefony
59 New Member
is there any chance that would work?
Oct 28 '09 #6
gits
5,390 Recognized Expert Moderator Expert
@Dormilich
wouldn't that be similar to:

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

@gits: looks like that.
Oct 28 '09 #8
gits
5,390 Recognized Expert Moderator Expert
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
freefony
59 New Member
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.  
Oct 29 '09 #10

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

Similar topics

5
2575
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> <name>array_push</name> <examples> <example> <name>A way to do it</name>
11
2119
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 pages for processing. The problem is, the user inputs can become very complex, and the way this application was developed, the inputs are all concatenated into monstrously long strings of text that are then submited as <hidden> inputs in HTML forms...
4
2660
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'. <txtNameUSState>CALIFORNIA</txtNameUSState>
0
6474
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, 'b_id' => 9, 'c_id' => 3,
3
2466
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 ? Thanks
9
1992
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 ArrayList? I have tried looping through the logfile using regex, if statements and flags to find the start and end of each message but I do not see a good time in this process to create a new instance of my Message object. While messing around with...
3
3292
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 "Searching..." page then, refreshes and displays the table I want. I have code that grabs data from the page using cURL but when I look at the data it contains the "Searching..." page and not the table that I want. below is the code i have so far....Thanks...
6
2397
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 file of the general form shown below. I dont have any definition of the data. Basically it looks like it is hierarchical, token/data pairs defined by brackets and square brackets. I would like to parse this out into some sort of data object(s) in...
1
2884
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 expressed in JS, the closer you'll get to rewriting a JS interpreter. For instance, this is not so hard to understand: "http://example.com/" but this is:
0
9718
marktang
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10613
Oralloy
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.